Sizeof () applies to structure and variable

consider the following snippet:

struct foo { int a; int b; int c; }; struct foo f; printf("%u, %u\n", sizeof(struct foo), sizeof(f)); 

The code returns the same values, but I was wondering if the sizeof () parameter is correct for the variable, or is it just a coincidence?

Thanks.

+6
source share
4 answers

Both will and should really return the same value.

From MSDN:

Sizeof operator
The sizeof operator gives the amount of memory in bytes needed to store an object of type operand. This operator avoids specifying machine-specific file sizes in your programs.

 sizeof unary-expression sizeof ( type-name ) 
+6
source

sizeof works with types and expressions. When you apply it to a type, () is part of the syntax sizeof : sizeof(type) . When you apply it to expression () , they are not part of the syntax sizeof : sizeof expression .

So, your second sizeof doesn't really apply to the variable. "It applies to the expression (f) . This expression consists of one variable f enclosed in an extra pair () . You can also do without this extra pair () and use only sizeof f .

When sizeof is applied to an expression, it returns the size of the result of the expression (i.e. the size of the type that this expression has). In your example, both sizeof applications are guaranteed to evaluate the same value.

In fact, a good programming practice is to avoid sizeof(type) as much as possible, i.e. prefer to use sizeof expression . This makes your code more type independent, which is always good. Type names belong to declarations and nowhere else.

+5
source

This is as expected, i.e. both will return the same value. This value is calculated at compile time.

It is generally recommended that you use a variable in sizeof , as you can change the type later, and therefore, the size can also change.

+1
source

In general, it is preferable to apply it to a variable. Then it will remain correct if the type of the variable changes.

0
source

Source: https://habr.com/ru/post/897009/


All Articles