Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sizeof operator Implementation : How it computes size at compile time?

Tags:

c

sizeof

Sizeof operator is compile time operator. converts sizeof expression with constant result values during compile time. [Exception variadic templates c99]

Normally compiler fixes size for variables at compile time. for array n. But when i print sizeof array it gives correct size? is this code allots memory at compile time for n?

How sizeof is evaluated then?

how about the array a[] in function?

int fun(int n)
{
    char a[n+3];
    return sizeof(a);
}
int
main( )
{
    int i;
    while(i!=-1){
        scanf("%d",&i);
        int n[i];
        printf("\nsize: %d %d\n",fun(3),sizeof n);
    }
}

when i try this : sizeof prints size of n correctly [(sizeof (int)) * i] but the function gives wrong results always 6?

How sizeof is implemented and calculates size (for float,int,...datatypes , variables, array, ...) ?

Any code is appreciated!

like image 346
Dineshkumar Avatar asked Dec 16 '22 10:12

Dineshkumar


2 Answers

As you mention, sizeof calculations are normally made at compile time, by the compiler. That's not always true (for example, C99/C11 variable length arrays), but it's a reasonable approximation.

Since the compiler knows (or decides) the size of every type, it can just make a simple constant substitution during compilation.

For your examples, a and n are both variable length arrays, and the sizeof operator is applied at runtime.

From C11, Section 6.5.3.4 The sizeof and _Alignof operators, paragraph 2:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

Editorial note: sizeof returns a size_t, not an int, so you should use a %zu format specifier instead of %d. Your compiler may warn you if you turn on the appropriate flags.

like image 93
Carl Norum Avatar answered Jan 04 '23 22:01

Carl Norum


Wikipedia explains the implementation of sizeof pretty well, See here for detail.

It is the responsibility of compilers to implement the sizeof operator correctly for each target platform. In many cases, there will be an official Application Binary Interface (ABI) document for the platform, specifying formats, padding, and alignment for the data types, to which the compiler must conform. In most cases, sizeof is a compile-time operator, which means that during compilation sizeof expressions get replaced by constant result-values. However, sizeof applied to a variable length array, introduced in C99, requires computation during program execution.`

like image 43
Yu Hao Avatar answered Jan 05 '23 00:01

Yu Hao