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

Viewed 90

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 
2 Answers

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).

It could, I mean c++ repurposes the auto keyword for this, but C was designed as a systems programming language and being able to write to memory as one type and read as another is very natural in that space (Implementation defined obviously, but just what about systems programming is not?).

Sometimes it is the underlying hardware that is writing to a memory region (array of bytes) and you want to read the word at offset 0x16 as an int32, and the short at offset 0x12 as a int16_t and so on, sometimes, just to fuck with developers the underlying data is TLV or has a variable length header so even the offsets have to be found by reading earlier data, and it does not overlay a struct in a sane way (RTP headers, looking at YOU, also .wav files)....

In this world explicitly declaring a pointer type is way more natural then inferring one.

Related