#include<stdio.h>
int main()
{
printf("%d\n", sizeof(2147483648));
printf("%d" , sizeof(2147483647+1));
return 0;
}
Output:
8
4
I understand that sizeof(2147483648)
is 8 bytes as it cannot fit in 4 bytes and is promoted to long long int
. But I do not understand what happens in case of sizeof(2147483647+1)
I found a similar question but it does not discuss the second case.
The rules of integer constant in C is that an decimal integer constant has the first type in which it can be represented to in:
int
,long
,long long
.does not fit into an
int
into your system (as the maximumint
in your system is2147483647
) so its type is along
(or along long
depending on your system). So you are computingsizeof (long)
(orsizeof (long long)
depending on your system).is an
int
in your system and if you add1
to anint
it is still anint
. So you are computingsizeof (int)
.Note thatsizeof(2147483647+1)
invokes undefined behavior in your system asINT_MAX + 1
overflows and signed integer overflows is undefined behavior in C.Note that while generally
2147483647+1
invokes undefined behavior in your system (INT_MAX + 1
overflows and signed integer overflows is undefined behavior in C),sizeof(2147483647+1)
does not invoke undefined behavior as the operand ofsizeof
in this case is not evaluated.