Consider the program
main()
{
printf("%d %d %d",sizeof('3'),sizeof("3"),sizeof(3));
}
output from a gcc compiler is:
4 2 4
Why is it so?
You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.
Need of sizeof() operator Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator: int *ptr=malloc(10*sizeof(int));
sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of char-sized units. Consequently, the construct sizeof (char) is guaranteed to be 1.
In C language, sizeof( ) is an operator. Though it looks like a function, it is an unary operator. For example in the following program, when we pass a++ to sizeof, the expression “a++” is not evaluated. However in case of functions, parameters are first evaluated, then passed to function.
Assuming you are running on a 32-bit system:
sizeof a character literal '3' is 4 because character literals are ints in C language (but not C++).
sizeof "3" is 2 because it is an array literal with length 2 (numeral 3 plus NULL terminator).
sizeof literal 3 is 4 because it is an int.
A few points to keep in mind:
sizeof
isn't a function, it's an operator. It returns the size of a type in units of sizeof char
. In other words sizeof char
is always 1.int
char[2]
, the character 3 then the null terminator.int
With these the differences are easily explained:
int
requires 4 char
s of space to hold itchar[2]
naturally only requires 2 char
sIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With