我有一个使用多种不同int类型的程序。
最常用的是uint64_t
和标准int
。但是我想知道我是否可以安全地在他们之间进行操作。
例如,我有uint64_t
,我想为其添加int
并将该值存储为另一个uint64_t
。
这样做是否安全?在我可以对其进行操作之前,是否必须将int
强制转换为uint64_t
?
我在网上找不到它的东西。它可能只是被允许,没有人质疑它或我的Google查询是错误的。
无论如何,基本上我的问题是我可以混合并使用不同类型的整数进行操作吗?
答案 0 :(得分:4)
是的,你可以。
您的编译器将负责转换。唯一要担心的是溢出 - 如果将结果存储在小于输入的容器中。
您需要的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.
---------------------------------------------+--------------------------------------------
答案 1 :(得分:0)
C
标准说,
如果具有无符号整数类型的操作数的秩大于或等于另一个操作数的类型的等级,则带有符号整数类型的操作数将转换为具有无符号整数类型的操作数的类型。
因此int
& unsigned int
具有相同的排名,您可以添加int
,unsigned int
转换为unsigned int
,将结果再次保留到{{1}}。