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

烂漫一生 提交于 2019-11-30 17:09:41

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:

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!