应用sizeof运算符时为什么会得到不同的结果? [英] Why do I get different results when I apply sizeof operator?

查看:89
本文介绍了应用sizeof运算符时为什么会得到不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个程序

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆