#include <stdio.h>
int main() {
char a = 'A';
int b = 90000;
float c = 6.5;
printf("%d ",sizeof(6.5));
printf("%d ",sizeof(90000));
printf("%d ",sizeof('A'));
printf("%d ",sizeof(c));
printf("%d ",sizeof(b));
printf("%d",sizeof(a));
return 0;
}
The output is:
8 4 4 4 4 1
Why is the output different for the same values?
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. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.
The sizeof operator is the most common operator in C. It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables.
If we try to increment the value of x, it remains the same. This is because, x is incremented inside the parentheses and sizeof() is a compile time operator.
Constants, like variables, have a type of their own:
6.5
: A floating point constant of type double
90000
: An integer constant of type int
(if int
is 32 bits) or long
(if int
is 16 bits)'A'
: A character constant of type int
in C and char
in C++The sizes that are printed are the sizes of the above types.
Also, the result of the sizeof
operator has type size_t
. So when printing the proper format specifier to use is %zu
, not %d
.
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