应用sizeof运算符时为什么会得到不同的结果? [英] Why do I get different results when I apply sizeof operator?
问题描述
我有这个程序
#include <stdio.h>
int main()
{
char arr[100];
printf("%d", (int)sizeof(0,arr));
}
当编译为C文件时,此命令输出4;作为C ++文件时,其输出100.为什么?我正在使用gcc.
This prints 4 when compiled as a C file and prints 100 as a C++ file. Why? I am using gcc.
推荐答案
在C中,逗号运算符的右操作数的结果具有类型和 value .在C中,逗号运算符不会产生左值.因此,存在从左值到右值的转换,从而导致数组类型转换为指针类型.因此,在C语言中,得到的是sizeof(char*)
的结果.
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*)
.
在C ++中,逗号表达式的结果是一个左值.没有这种转换(如在C中),您得到的是sizeof(arr)
即100
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运算符时为什么会得到不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!