Reputation: 3564
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
Upvotes: 3
Views: 52048
Reputation: 137810
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 int
and int
are 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-byte long int
would be left uninitialized.
EDIT: Asking "but will it crash" is thinking the wrong way. Merely reading uninitialized bytes into a variable of type long int
is 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.
Upvotes: 5
Reputation: 4952
Usually on 32 bit systems long int have 32 bits (same as int) and on 64 bits system long int have 64 bits (same as long long int). If you want your code to be portable, use scanf with "%ld".
Upvotes: 0
Reputation: 6776
As RageD says, you really should use %ld in the scanf()
call. The reason why it works is because on your system (or so it appears to me), int
and long int
are the same size (probably 4), so scanf()
does not overwrite any memory it shouldn't.
Upvotes: 1