5

Is there any expression that would be evaluated as operand of a sizeof. I have come to know in case of variable length operand with sizeof, the expression would be evaluated. But I cant make an example, I wrote the code below,

int a[]={1,2,3};
printf("%d",sizeof(a[1]++));
printf("%d\n",a[1]);

but here I observed from output expression a[1]++ is not evaluating. how to make an example??

amin__
  • 1,018
  • 3
  • 15
  • 22
  • 1
    Well, `a[1]++` isn't a variable length array, so it's not evaluated. – Daniel Fischer Jul 10 '12 at 19:28
  • @DanielFischer: His confusion is why 1++ is not evaluated by `sizeof` as a 4 byte integer. –  Jul 10 '12 at 19:29
  • 1
    @0A0D DanielFisher's reply is correct. `sizeof` doesn't evaluate its operand unless it's a variable length array. http://stackoverflow.com/questions/1995113/strangest-language-feature/2018786#2018786 – Alok Singhal Jul 10 '12 at 19:34
  • @Alok: I missed the point due to the half prose in the question.. I read it three times before it made sense now. –  Jul 10 '12 at 19:37

1 Answers1

6

Your array is not a variable-length array. A variable length array is an array whose size is not a constant expression. For example, data is a variable-length array in the following:

int i = 10;
char data[i];

To see an example of a code that has sizeof evaluate its operand, try something like this:

#include <stdio.h>

int main(void)
{
    int i = 41;
    printf("i: %d\n", i);
    printf("array size: %zu\n", sizeof (char[i++]));
    printf("i now: %d\n", i);
    return 0;
}

It prints:

i: 41
array size: 41
i now: 42
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
  • @amin__: It says take a `char` array of size 41, increase the integer holding the size by `1` and then assign that number (`42`) to the size of the char array, which becomes `42`. –  Jul 10 '12 at 20:02
  • But where is that char array?? I see it is not exist. Can the char array of size 42 now be used? – amin__ Jul 10 '12 at 20:06
  • @amin__: sizeof can be used with types and expressions. It's creating a temporary array for the sake of evaluating a useless variable length array because it is not used beyond that. –  Jul 10 '12 at 20:07
  • @Alok why dont you use data array(as it is also variable length array) instead of `char[i++]` in sizeof?? – amin__ Jul 10 '12 at 20:16
  • @amin__ Because you can't observe the evaluation of the expression with `data`. You need an expression with an observable side effect, the temporary `char[i++]` does just that. – Daniel Fischer Jul 10 '12 at 20:19
  • @DanielFischer, I was wondering if any usable variable length array gives the observable output..anyway thank you all – amin__ Jul 10 '12 at 20:37