选型在C字面数值 [英] Type selection for literal numeric values in C

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

问题描述

我想了解一下:当我尝试分配一个整数值到 INT 变量(16位编译器,2个字节的整数)让我们说:

I'm wondering about this: when I try to assign an integer value to an int variable (16-bit compiler, 2 bytes for integers) let's say:

int a;

a=40000;

这不能被重新使用,将被截断的类型的范围psented $ P $。但我所看到的是,在所得到的值 是-25000这意味着位模式(或一些亲密号码)编译器选择十进制40000二进制重新presentation重新presentation无符号整数。并引发我的问题:编译器如何选择这个文字前pression类型?

that can't be represented with the range of the type it will be truncated. But what I'm seeing is that the resulting value in a is the bit pattern for -25000 (or some close number) which means that the binary representation that the compiler chooses for decimal 40000 was unsigned integer representation. And that raises my question: how does the compiler choose the type for this literal expression?

我猜测它使用能够与需要更少的存储空间处理值的类型。

I'm guessing it uses the type capable of handling the value with less storage space needed.

推荐答案

下面行为C89和C99之间是不同的。

Behaviour here differs between C89 and C99.

在C89,一个十进制整数文字采用第一个这种类型中,它可以重新presented的:

In C89, a decimal integer literal takes the first of these types in which it can be represented:

int, long, unsigned long

在C99,一个十进制整数文字采用第一个这种类型中,它可以重新presented的:

In C99, a decimal integer literal takes the first of these types in which it can be represented:

int, long, long long

有关特定code片段没什么区别,因为40000是保证适合在长,但也有C89和C99文字之间的一些差异显著

For your particular code snippet it makes no difference, since 40000 is guaranteed to fit in a long, but there are a few significant differences between C89 and C99 literals.

其中的一些后果描述如下:

Some of those consequences are described here:

http://www.hardtoc.com/archives/119

这篇关于选型在C字面数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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