Why do I get different results when I apply sizeof operator? Why do I get different results when I apply sizeof operator? arrays arrays

Why do I get different results when I apply sizeof operator?


In C the result of the right hand operand of the comma operator has a type and value. In C a comma operator does not yield an lvalue. So there is an lvalue to rvalue conversion resulting in decay of array type to pointer type. So in C what you get is the result of sizeof(char*).

In C++ the result of a comma expression is an lvalue. There is no such conversion[as in C] and what you get is the sizeof(arr) i.e 100


sizeof is an operator not a function

So, you are executing the comma operator, which returns the right operand as its result.

In C++, this is a reference, so it's still an array and has its full size.

In C, in an expression (anything with an operator) normally the type array of x is converted to pointer to x. But there is a specific exception for two operators: sizeof and &.

So it matters if sizeof gets there first or not, because of the exception to the conversion rules. (See C99 section 6.3.2.1.)

You can see this another way, and here the program returns the same thing in C and C++.

#include <stdio.h>int main(void) {  char arr[100];  printf("%d\n", (int)sizeof arr);  printf("%d\n", (int)sizeof(arr + 0));  return 0;}

result on my Mac:

1008

† 6.3.2.1(3) Except when it is the operand of the sizeof operator or the unary & operator, or is astring literal used to initialize an array, an expression that has type ‘‘array of type’’ isconverted to an expression with type ‘‘pointer to type’’ that points to the initial element ofthe array object and is not an lvalue.