user724619
user724619

Reputation: 287

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

I have this program

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

This prints 4 when compiled as a C file and prints 100 as a C++ file. Why? I am using gcc.

Upvotes: 20

Views: 649

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146261

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:

100
8

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

Upvotes: 3

Prasoon Saurav
Prasoon Saurav

Reputation: 92942

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

Upvotes: 34

Related Questions