%d with Long Int

47,438

Solution 1

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.

Solution 2

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.

Share:
47,438
nikel
Author by

nikel

Another guy who like programming:P...B.Tech,Computer Science.I believe that Programming is the art of making perfect things.

Updated on April 26, 2020

Comments

  • nikel
    nikel almost 4 years

    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