2
#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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It might also put them in the 4 most significant positions. You'll get consistent results, but they'll be the "expected" result multiplied by 2^32.
Great answer. Note that on a big-endian architecture, you might still not get the expected output after zeroing because the value is placed in the 4 most significant bytes instead.
Initializing the variables to 0 would not produce the expected output for negative input values such as -123 in the OP's question.
3

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.

1 Comment

That is supported by OP's example output of 235046380240896 which has the bottom 32 bits all zero (0xD5C600000000).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.