Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sizeof operator with variable-length array type

According to cppreference:

If the type of expression is a variable-length array type, expression is evaluated and the size of the array it evaluates to is calculated at run time.

It means: if the type of expression is a VLA type, then expression is evaluated. For example:

#include <stdio.h>

int main() {
    int i = 0;
    int a[i];
    printf("%zu\n",sizeof(a[i++]));
    printf("%d\n",i); // Here, print 0 instead of 1
    return 0;
}

So, according to the reference, here i becomes 1. But, with my GCC compiler, i prints as 0.

See Wandbox Demo.

like image 245
msc Avatar asked Feb 07 '18 10:02

msc


People also ask

What is variable length array type?

In computer programming, a variable-length array (VLA), also called variable-sized or runtime-sized, is an array data structure whose length is determined at run time (instead of at compile time). In C, the VLA is said to have a variably modified type that depends on a value (see Dependent type).

Does sizeof work on arrays?

The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function. In this code, the A object is an array and the sizeof(A) expression will return value 100.

How does sizeof know array size?

sizeof(type) gives you the number of bytes of the type you pass. Now if you pass array then the compiler knows that this is an array and number of elements in it and it just multiplies that many elements with the respective data-type size value.

What is sizeof in C array?

The sizeof operator on an array returns the total memory occupied by the array in bytes. To determine the total number of the array elements, the trick is to divide the total memory occupied by the array by the size of each element. This is demonstrated below in C: 1.


1 Answers

First of all, please note that an array cannot have size zero, be it a VLA or not. So your code invokes undefined behavior.

C11 6.7.6.2/5

"If the size is an expression that is not an integer constant expression:" /--/ "...each time it is evaluated it shall have a value greater than zero."


As for the actual problem, a[i++] is of type int, not of VLA type.

In order to get the side-effect, you must involve the VLA array type itself, such as sizeof(a). Only then is the operand evaluated for side effects. One example to illustrate this:

#include <stdio.h>

int main() {
    int i=1, j=1;
    int a[i][j];
    int b[1][1];

    (void) sizeof(a[--i]);
    (void) sizeof(b[--j]);
    printf("%d %d", i, j);

    return 0;
}

Here i ends up as 0 since the first sizeof is evaluated because of the VLA, but j remains 1 because --j was part of a sizeof for a regular array.

like image 82
Lundin Avatar answered Nov 09 '22 15:11

Lundin