Reputation: 3927
I have this code below:
#include <stdio.h>
int main(void) {
int i = "hello world";
printf("%d", i);
return 0;
}
why assigning a string
to int
variable not giving me a compilation error, but prints a garbage value.
Edit 1:
A lot of answers suggested to not ignore the warning. I wrote this code on ideone, which unfortunately, did not give me any warning.
Upvotes: 0
Views: 1344
Reputation: 15062
int i = "hello world";
With that you assigning the address of the string literal "hello world"
in memory to the int
object i
, which is in most cases undefined behavior because the value of a memory location is in many cases beyond the area an object of type int
can hold.
This undefined value is then printed by:
printf("%d", i);
Nonetheless the compiler should give you a warning when doing that without an explicit cast, f.e. as I compiled your code by gcc it gave:
warning: initialization of 'int' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
Do never ignore compiler warnings.
Upvotes: 1
Reputation: 41
I believe it would perform a pointer to int conversion. It should be a warning indicating the conversion without cast.
Upvotes: 2