具有不同int类型的操作

我有一个程序,它使用多种不同的int类型。

最常用的是uint64_t和标准int 。 但是我想知道我是否可以安全地在他们之间进行混合操作。

例如,我有一个uint64_t ,我想为它添加一个int并将该值存储为另一个uint64_t

做这样的事情安全吗? 在我可以对它进行操作之前,是否必须将intuint64_t

我不能在网上找到关于它的东西。 它可能只是被允许,没有人质疑它或我的谷歌查询是错误的。

无论如何,基本上我的问题是我可以混合并使用不同类型的整数进行操作吗?

是的你可以。

您的编译器将负责转换。 唯一要担心的是溢出 – 如果将结果存储在小于输入的容器中。

您需要的Google搜索字词是“隐式类型转换” – 请参阅http://pic.dhe.ibm.com/infocenter/ratdevz/v8r5/index.jsp?topic=%2Fcom.ibm.tpf.toolkit.compilers .DOC%2Fref%2Flangref_os390%2Fcbclr21011.htm

该链接包括下表:

算术转换按以下顺序进行:

 Operand Type Conversion ---------------------------------------------+-------------------------------------------- One operand has long double type | The other operand is converted to long double type. ---------------------------------------------+-------------------------------------------- One operand has double type | The other operand is converted to double. ---------------------------------------------+-------------------------------------------- One operand has float type | The other operand is converted to float. ---------------------------------------------+-------------------------------------------- One operand has unsigned long long int type | The other operand is converted to unsigned long long int. ---------------------------------------------+-------------------------------------------- One operand has long long int type | The other operand is converted to long long int. ---------------------------------------------+-------------------------------------------- One operand has unsigned long int type | The other operand is converted to unsigned long int. ---------------------------------------------+-------------------------------------------- One operand has unsigned int type | and the other operand has long int type | and the value of the unsigned int can be | represented in a long int | The operand with unsigned int type is converted to long int. ---------------------------------------------+-------------------------------------------- One operand has unsigned int type | and the other operand has long int type | and the value of the unsigned int cannot be | represented in a long int | Both operands are converted to unsigned long int ---------------------------------------------+-------------------------------------------- One operand has long int type | The other operand is converted to long int. ---------------------------------------------+-------------------------------------------- One operand has unsigned int type | The other operand is converted to unsigned int. ---------------------------------------------+-------------------------------------------- Both operands have int type | The result is type int. ---------------------------------------------+-------------------------------------------- 

C标准说,

如果具有无符号整数类型的操作数的秩大于或等于另一个操作数的类型的秩,则具有有符号整数类型的操作数将转换为具有无符号整数类型的操作数的类型。

因此,因为intunsigned int具有相同的级别,所以可以添加它们,并且当您添加它们时, int将转换为unsigned int ,将结果再次保留为unsigned int