C: What happens technically when int type is stored in long long type?

Viewed 83
#include <stdio.h>

int main() {
    long long a, b;
    scanf("%d %d", &a, &b);
    printf("%lld", a + b);
    return 0;
}

The code above reads two numbers and prints the sum of them. I know the precise one should use format specifier %lld rather than %d, which I believe is the cause of compiling error.

However, the problem is that some compilers, such as https://www.programiz.com/c-programming/online-compiler/, execute the code without any syntax error but print awkward value like below, which I don't get it at all.

Input: 123 -123
Output: 235046380240896 (This value consistently changes)

What is happening on the foundational level when int type is stored in long long type?

2 Answers

Formally it is undefined behavior, since the format specifiers don't match the type. So anything can happen in theory. Compilers aren't required to give diagnostics for mismatching format strings vs variables provided.

In practice, many (32/64 bit) compilers likely read 4 bytes and place them in the 4 least significant positions (little endian) of the the long long, whereas the upper 4 most significant bytes maintain their indeterminate values - that is, garbage, since the variable was never initialized.

So in practice if you initialize the long long to zero you might actually get the expected output, but there are no guarantees for it.

This is undefined behavior, so anything could happen. What's most likely happening in practice is that scanf() is storing the numbers you enter into 32 bits halves of each 64-bit long long variable. Since you never initialized the variable, the other halves contain unpredictable values. This is why you're getting a different result each time.

Related