Why do we say sizeof(variable)
is an operator, not a function?
It looks like a function call and when I am thinking about the meaning of operator, it appears to me something like +
or -
or *
and so on
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.
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.
sizeof operator: sizeof is much used in the C/C++ programming language. It is a compile-time unary operator which can be used to compute the size of its operand.
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.
It's an operator, and you don't need to use brackets, except "when the operand is a type name, it must be enclosed in parentheses". This is a syntax restriction, but should not be confused with a function call.
See the last example below from the GNU documentation:
size_t a = sizeof(int);
size_t b = sizeof(float);
size_t c = sizeof(5);
size_t d = sizeof(5.143);
size_t e = sizeof a;
Without parentheses for a type name, you may see an error like this, with the gcc compiler:
test.c:7:20: error: expected expression before ‘int’
7 | size_t s = sizeof int;
| ^~~
But doing sizeof 12
or sizeof a
is fine.
It's an operator because it doesn't take arguments like a function does. It operates at the syntax level.
f(int)
is not a valid function call, but sizeof(int)
is a valid use of sizeof
.
It can also operate on variables or types, it's quite flexible by design, which is something an operator can do as it's baked deep into the C syntax.
More details can be found here.
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