Reputation: 13
Let's start with this example:
#include <stdio.h>
int main()
{
int x = "string";
printf("%d", x);
}
Ouput -> "12221232"
I know this code example is syntactically correct semantically false. I just don't know what happens here exactly. The text gets converted into an integer, but how? Can someone please explain?
Upvotes: 0
Views: 104
Reputation: 213296
int x = "string";
is a constraint violation of simple assignment, see "Pointer from integer/integer from pointer without a cast" issues.
So the code is not valid C, has never been valid C and will not compile cleanly, see What must a C compiler do when it finds an error?. Speculating about why an invalid, non-standard C program prints something isn't very meaningful.
Upvotes: 0
Reputation: 222302
In int x = "string";
, two things of note happen:
"string"
is automatically converted to a pointer to its first element. So this is some address in memory, of type char *
.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.
Upvotes: 2
Reputation: 87054
It's not converting the text to an integer, it is printing the value memory location of the literal string
. Try this:
#include <stdio.h>
int main()
{
int x = "string";
printf("x = %d\n", x);
printf("string = %d\n", "string");
}
If you run this you'll see that x
and the literal "string"
have the same memory address.
Sample output
x = 4202512
string = 4202512
Although as @pmg commented, this is not necessarily the case.
In summary, what you are seeing is that the address of the string "string"
is being assigned to x
, which is where x
is getting this value.
Upvotes: 0
Reputation: 14107
The value you observe is an address where "string"
is stored.
The literal "string"
is actually cast to a pointer of type const char *
that points to the actual data. This pointer (address of "string"
data) is next cast to int
which you observe as output of printf()
.
Upvotes: 3