evaluation of expression which is used with sizeof
Asked Answered
N

1

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??

Negligible answered 10/7, 2012 at 19:27 Comment(4)
Well, a[1]++ isn't a variable length array, so it's not evaluated.Deanndeanna
@DanielFischer: His confusion is why 1++ is not evaluated by sizeof as a 4 byte integer.Evslin
@0A0D DanielFisher's reply is correct. sizeof doesn't evaluate its operand unless it's a variable length array. https://mcmap.net/q/16355/-strangest-language-feature/…Nixie
@Alok: I missed the point due to the half prose in the question.. I read it three times before it made sense now.Evslin
N
7

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
Nixie answered 10/7, 2012 at 19:55 Comment(6)
@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.Evslin
But where is that char array?? I see it is not exist. Can the char array of size 42 now be used?Negligible
@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.Evslin
@Alok why dont you use data array(as it is also variable length array) instead of char[i++] in sizeof??Negligible
@Negligible 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.Deanndeanna
@DanielFischer, I was wondering if any usable variable length array gives the observable output..anyway thank you allNegligible

© 2022 - 2024 — McMap. All rights reserved.