Richard Tobin said:
Keith Thompson said:
Can anyone think of a case where the evaluation of the argument of
sizeof (when it's a VLA) has a visible effect on the behavior of the
program?
Gcc with flags "-std=c99 -pedantic -Wall' thinks the following program
is legal:
#include <stdio.h>
int main(void)
{
int n = 42;
printf("%d\n", (int)sizeof(char [n++]));
printf("%d\n", (int)sizeof(char [n++]));
return 0;
}
and it prints:
42
43
While it seems logic to do so, the language of the standard is not clear:
6.5.3.4p2: "... 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."
What if the type of char[n++] ?
How can we evaluate char[n++] ?
char [n++] *is* a type, it does not *have* a type.
I don't think the language of the standard correctly specifies what should
be the behaviour of such code.
A more compelling example would be
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
if (argc > 1) {
int n = strtol(argv[1], NULL, 0);
int matrix[n][n];
int i = 1;
printf("i=%d, n=%d\n", i, n);
printf ("sizeof(matrix) = %zd\n", sizeof(matrix));
printf ("sizeof(matrix[i++]) = %zd\n", sizeof(matrix[i++]));
printf("i=%d\n", i);
printf ("sizeof(char[i++]) = %zd\n", sizeof(char[i++]));
printf("i=%d\n", i);
}
return 0;
}
with gcc upto version 4.1.3, I get what I interpret as non conforming
behaviour:
$ ./vla 2
i=1, n=2
sizeof(matrix) = 16
sizeof(matrix[i++]) = 8
i=1
sizeof(char[i++]) = 1
i=2
I think we have a defect here: the argument to sizeof should be evaluated is
it *is* a variable length array type, not if it is an expression whois type
can be determined from static analysis.