2

Consider please

#include <stdio.h>
 
int main(void) {    
    int size = 1;
    int foo[1];
    int bar[size];
 
    int* pfoo = 0;
    int* pbar = 0;
 
    printf("%zu %zu\n", sizeof(pfoo = foo), sizeof(pbar = bar));
    printf("%p %p\n", pfoo, pbar);
 
    return 0;
}

The output when running this on https://ideone.com/VeiJXH is

8 8

(nil) (nil)

I was expecting pbar to be set to the address of the first element of bar, as bar is a variable length array. I thought that sizeof was evaluated at runtime for variable length arrays, which would mean that pbar would be non-zero.

What's going on? This is not a quiz; it's a cut down version of a problem that I've encountered in my code.

Edit: I don't think the duplicate helps here - my question is about sizeof not being evaluated for a variable length array.

Community
  • 1
  • 1

1 Answers1

7

The type of an assignment is "the value of the left operand after the assignment" (§6.5.16/3, emphasis added). In the case of pbar = bar, the left operand's value is of type int* (since that's what pbar is).

With respect to the sizeof operator, "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." (§6.5.3.4/2). As above, the type of the operand is int*, which is not a variable-length array type. So no evaluation takes place.

The following is really a bad idea. But it gives an idea of a circumstance in which evaluation would occur:

printf("%zu\n", sizeof(int[dim = x + y]));
printf("%d\n", dim);
rici
  • 234,347
  • 28
  • 237
  • 341