#include <stdio.h> #include <string.h> int main(void) { char ch='a'; printf("sizeof(ch) = %d\n", sizeof(ch)); printf("sizeof('a') = %d\n", sizeof('a')); printf("sizeof('a'+'b'+'C') = %d\n", sizeof('a'+'b'+'C')); printf("sizeof(\"a\") = %d\n", sizeof("a")); }
This program uses sizeof
to calculate sizes. Why is the size of 'a'
different from the size of ch
(where ch='a'
)?
sizeof(ch) = 1 sizeof('a') = 4 sizeof('a'+'b'+'C') = 4 sizeof("a") = 2
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.
Value 100 in the square brackets indicates to the programmer that he is working with an array of 100 items. But it is not an array of a hundred items which is passed into the function - it is only the pointer. So, the sizeof(B) expression will return value 4 or 8 (the size of the pointer in a 32-bit/64-bit system).
The sizeof keyword refers to an operator that works at compile time to report on the size of the storage occupied by a type of the argument passed to it (equivalently, by a variable of that type). That size is returned as a multiple of the size of a char, which on many personal computers is 1 byte (or 8 bits).
Answer: sizeof returns the size of the type in bytes.
TL;DR - sizeof
works on the type of the operand.
sizeof(ch)
== sizeof (char)
-------------------(1)sizeof('a')
== sizeof(int)
--------------------(2)sizeof ('a'+ 'b' + 'c')
== sizeof(int)
---(3)sizeof ("a")
== sizeof (char [2])
----------(4)Let's see each case now.
ch
is defined to be of char
type, so , pretty straightforward.
In C, sizeof('a')
is the same as sizeof (int)
, as a character constant has type integer.
Quoting C11
,
An integer character constant has type
int
. [...]
In C++, a character literal has type char
.
sizeof
is a compile-time operator (except when the operand is a VLA), so the type of the expression is used. As earlier , all the integer character constants are of type int
, so int
+ int
+ int
produces int
. So the type of the operand is taken as int
.
"a"
is an array of two char
s, 'a'
and 0
(null-terminator) (no, it does not decay to pointer to the first element of the array type), hence the size is the same as of an array with two char
elements.
That said, finally, sizeof
produces a result of type size_t
, so you must use %zu
format specifier to print the result.
If 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