Why no switch on pointers?

A switch compares the variable with a set of compile-time constants. Other than null, I can't see any valid compile time constants that you might compare a pointer with. For example:

switch (ptr) { 
   case &var1: printf ("Pointing to var1"); break;
   case &var2: printf ("Pointing to var2"); break;
}

var1 and var2 are likely different in each run of the program, and would not be compile time constants. One possibility might be that they are addresses of memory-mapped ports that are always fixed, but otherwise I don't see how you could easily expand this from your two cases (null / not-null).


switch statements operate on integral expressions only. A pointer is not an integral expression.

You can explicitly convert a pointer to an integral type if you wanted to, but the proposed code is a little strange and unnatural.

So to answer your question exactly: Because there is no implicit conversion between a pointer and an integral type.


Switch statements operate on integral values only. That's why the error message is "switch quantity not an integer." I don't think it's a technical limitation so much as it's outside the language syntax.


Because there is only one constant pointer expression

Given that only a single constant pointer expression exists, the switch statement has little to offer pointer expressions. You have cited essentially the only possible construction.