Why is it that I can assign a string to a variable of type int? Eg. the following code compiles correctly:
int main(int argv, char** argc){
int a="Hello World";
printf(a);
}
Also, the program doesn’t compile when I assign a string to a variable of a different type, namely double and char.
I suppose that what is actually going on is that the compiler executes int* a = "Hello World"; and when I write double a="Hello World";, it executes that line of code as it is.
Is this correct?
In fact, that assignment is a constraint violation, requiring a diagnostic (possibly just a warning) from any conforming C implementation. The C language standard does not define the behavior of the program.
EDIT : The constraint is in section 6.5.16.1 of the C99 standard, which describes the allowed operands for a simple assignment. The older C90 standard has essentially the same rules. Pre-ANSI C (as described in K&R1, published in 1978) did allow this particular kind of implicit conversion, but it’s been invalid since the 1989 version of the language.
What probably happens if it does compile is that
is treated as it if were
The cast takes a pointer value and converts to int. The meaning of such a conversion is implementation-defined; if
char*andintare of different sizes, it can lose information.Some conversions may be done explicitly, for example between different arithmetic types. This one may not.
Your compiler should complain about this. Crank up the warning levels until it does. (Tell us what compiler you’re using, and we can tell you how to do that.)
EDIT :
The
printfcall:has undefined behavior in C90, and is a constraint violation, requiring a diagnostic, in C99, because you’re calling a variadic function with no visible prototype. If you want to call
printf, you must have a(In some circumstances, the compiler won’t tell you abut this, but it’s still incorrect.) And given a visible declaration, since
printf‘s first parameter is of typechar*and you’re passing it anint.And if your compiler doesn’t complain about
you should get a better compiler. That (probably) tries to convert a pointer value to type
double, which doesn’t make any sense at all.