C中整数表达式的大小 [英] sizeof an integer expression in C

查看:79
本文介绍了C中整数表达式的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Xcode编译C(gnu11)让我感到惊讶

To my semi-surprise with Xcode compiling C (gnu11)

#include <stdio.h>
int main(int argc,char**argv)
{
    short s = 1;
    printf( "%zd %zd %zd\n", sizeof(s), sizeof(s*s), sizeof(s?s:s));
    return 0;
}

产生输出

2 4 4

我期待中

2 2 2

或可能

2 4 2

这是为什么?

推荐答案

我从K& R回忆起,任何小于int的整数表达式都被提升为int.我在标准(C89)中找到了这一点:

I recalled from K&R that any integer expression smaller than an int is promoted to int. I found this in Standard (C89):

3.2.1.1字符和整数

3.2.1.1 Characters and integers

一个字符,一个简短的int或一个int位字段,或者它们的有符号或 无符号变体或具有枚举类型的对象可能是 在可以使用int或unsigned int的表达式中使用的表达式.如果 一个int可以代表原始类型的所有值,该值为 转换为int;

A char, a short int, or an int bit-field, or their signed or unsigned varieties, or an object that has enumeration type, may be used in an expression wherever an int or unsigned int may be used. If an int can represent all values of the original type, the value is converted to an int;

令人惊讶的是s?s:s,因为我能找到的所有引用都说生成的类型是左值,但这只是C ++. C将其视为右值.如预期的那样,C ++的输出为:

The surprise is s?s:s because all reference I could find say the resulting type is an lvalue but that's just C++. C treats it as an rvalue. As expected then, C++'s output is:

2 4 2

即使表达式是一个右值. C和C ++之间的意外差异.

Even if the expression is an rvalue. An unexpected difference between C and C++.

这篇关于C中整数表达式的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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