Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is sizeof a function or an operator?

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

like image 416
Run Avatar asked Jan 22 '21 15:01

Run


People also ask

What is sizeof () in C operator or function?

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.

What kind of operator is sizeof?

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.

Is sizeof a valid operator in C?

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.

Is sizeof a unary operator?

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.


Video Answer


2 Answers

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.

like image 80
Nagev Avatar answered Oct 20 '22 22:10

Nagev


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.

like image 5
tadman Avatar answered Oct 21 '22 00:10

tadman