Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof(2147483648) is 8 bytes while sizeof(2147483647+1) is 4 bytes

Tags:

c

sizeof

#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.

like image 200
user2830528 Avatar asked Jun 21 '15 09:06

user2830528


People also ask

Why sizeof int is 4?

On a 32-bit Machine, sizeof(int*) will return a value 4 because the address value of memory location on a 32-bit machine is 4-byte integers. Similarly, on a 64-bit machine it will return a value of 8 as on a 64-bit machine the address of a memory location are 8-byte integers.

Why is a long 4 bytes?

The C++ Language Specification simply states that the size of a long must be at least the size of an int . It used to be standard to have int = 2 bytes and long = 4 bytes.

Is a long 4 bytes?

long and long long are both 8 bytes.

Is Long 4 bytes in C?

The integer data type is further divided into short, int, and long data types. The short data type takes 2 bytes of storage space; int takes 2 or 4 bytes, and long takes 8 bytes in 64-bit and 4 bytes in the 32-bit operating system.


1 Answers

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.

2147483648

does not fit into an int into your system (as the maximum int in your system is 2147483647) so its type is a long (or a long long depending on your system). So you are computing sizeof (long) (or sizeof (long long) depending on your system).

2147483647

is an int in your system and if you add 1 to an int it is still an int. So you are computing sizeof (int).

Note that sizeof(2147483647+1) invokes undefined behavior in your system as INT_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 of sizeof in this case is not evaluated.

like image 151
ouah Avatar answered Sep 29 '22 18:09

ouah