In int x = "string";
, two things of note happen:
- The array represented by
"string"
is automatically converted to a pointer to its first element. So this is some address in memory, of type char *
.
- The address is converted to an
int
.
This conversion is specified by C 2018 6.3.2.3 6, which says:
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined…
Footnote 69 tells us the implementation-defined conversion is supposed to be “consistent” with the addressing structure of the environment the program runs in. Most modern systems use a “flat” address space, so the result of converting an address to an int
will be the address as you may know it from seeing addresses in the debugger. But that is provided the address fits in an int
.
If your system uses eight-byte addresses and four-byte int
, then many addresses will not fit in an int
. In this case, the behavior is not defined. A common behavior is for C implementation to use just four bytes of the address to make the int
. Alternatively, it might set the int
to all zeroes or all ones, or it might leave “garbage” in the int
, or it might trap.