Is the following code Correct?As far as my understanding,it should not work properly,but on the Dev-C++ Compiler,it does.Could someone explain in detail please?
#include<limits.h>
int main()
{
long int num_case=LONG_MAX;
scanf("%d",&num_case);
printf("%ld",num_case);
return 0;
}
Thanks
Like most things that the standard C library tells you not to do, it invokes undefined behavior. Undefined means it might work under some conditions yet crash when you least expect it.
In this case, it works because
long intandintare actually the same numeric representation: four byte, two’s complement. With another platform (for example x86-64 Linux), that might not be the case, and you would probably see some sort of problem. In particular, the high-order bytes of the 8-bytelong intwould be left uninitialized.EDIT: Asking “but will it crash” is thinking the wrong way. Merely reading uninitialized bytes into a variable of type
long intis allowed to crash a C program, according to the language standard. We don’t need to find an example of a platform which does so, to understand that the program is ill-specified. That is the point. C does not throw the rulebook at you right away, it waits until you port and break initial assumptions.