Search code examples
cgccsizeofvariable-length-array

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.


Solution

  • 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.