cpointers

Why cant pointer type be inferred based upon the type of variable it points to?


Question: Is there any particular reason that if the complier knew an int goes into an address, then it cant remember that an int is there when reading?

  1. As I understand, line 0 tells the compiler to allocate 16 bits for whatever value will be placed there upon assignment in line 3.

  2. And I understand that one of the reasons for declaring the pointer type at line 1 is to tell the compiler how many bytes to read when dereferencing the pointer p with *p on line 6.

    0:    int i;
    1:    int *p;
    2:
    3:    i = 5;
    4:    p = &i;
    5:
    6:    printf("%d",*p);

For simplicity, using bit-width of 8 in mem table. Say i is written at 0x04 and p is written at 0x02.

  addr | storedVal  
 -----------------
  0x01 |           
  0x02 | 00000100 
  0x03 |          
  0x04 | 00000000 
  0x05 | 00000101 

Solution

  • It could be if the language allowed it; in C++, you could delay the declaration of p until the point of assignment and just do:

    auto p = &i;
    

    and it would infer that p is an int*. C doesn't do that though. It has no syntactic facility for deriving the type of an object, so you need to declare the type explicitly.

    If you're talking about printf, printf is a varargs function; it doesn't know the types of the variables passed to it (some compilers special case it for checks at compile time, but that's an implementation detail, not a language guarantee; at runtime it doesn't know). It only knows to look for an int because the %d placeholder told it to check for that (and no pointers are involved inside printf; it was passed the raw int read from the pointer, not a pointer to the int).