I was trying to understand the working of sizeof operator and I came across this question. Following is the code from that question
#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;
}
array a here is variable length but when its used as an oprand to the sizeof operator the variable i
is not incremented.
some of the comments and answer say that a[i++]
is not a VLA type and suggest that op should use a 2D VLA to see the side effect( sizeof evalutes its oprand).
I dont clearly understand why a[i++]
doesn't qualify as a VLA expression.i think it has something to do with the fact that we can leave the first dimension unspecified of an array while passing to a fucntion.
so the question is in general what is considered a VLA expression ?
I don't clearly understand why
a[i++]
doesn't qualify as a VLA expression
a[n]
is not a VLA expression, even though a
is a VLA, because the expression produces a single element of a VLA, not the VLA itself.
in general what is considered a VLA expression?
In your example, a
would be a VLA expression, because it represents a variable-length array.
A 2D VLA would give you a scenario where sizeof
would evaluate its operand:
int x, y;
scanf("%d %d", &x, &y);
int a[x][y];
int i = 0;
size_t z = sizeof(a[i++]);
printf("%d %d\n", i, (int)z);
This prints 1
, because now not only a
is a VLA, but a[n]
is a VLA as well (demo).