在这种情况下我们需要 Actor 吗?:
#include <stdio.h>
#include <stdint.h>
int main(){
// Say we're working with 32-bit variables.
uint32_t a = 123456789;
uint32_t b = 5123412;
uint32_t c = 123049811;
// We want to use 64-bit arithmetic at some intermediate stage,
// e.g. the a*b product here. After dividing by 'c', the result
// again fits into a 32-bit unsigned, 'result'.
uint32_t result = (uint64_t)a*b/c;
// QUESTION HERE: Should we cast before the assignment? I.e.:
//uint32_t result = (uint32_t)( (uint64_t)a*b/c );
// Either way the result turns out OK on my system.
printf("%u\n", (unsigned)result);
}
最佳答案
对于任何分配 a = b;
, b
的值被转换为 a
类型的值,前提是可能,并且转换后的值被分配给 a
。所以你提议的最外面的 Actor 是多余的。
但是,并非所有此类转换都是可能的,并且可以使用强制转换来强制转换,或者在不存在直接转换的情况下创建一系列合法转换,如下例所示:
foo x;
bar * y = (void *)&x;
没有从
foo *
到 bar *
的隐式转换,但是有从任何对象指针类型到和从 void *
的隐式转换(尽管未指定 y
是否具有可用或有用的值)。显式转换的另一个用途是当它改变一个值的含义时——一个典型的例子是当你想要将一个 I/O 字节视为一个无符号值时。由于
char
可以是有符号的或无符号的,将 char
直接转换为 unsigned int
可能会给出错误的答案。例如,我们希望 -1
是值 255,而不是 -1。所以你需要:char b = get_input();
unsigned int value = (unsigned char)b;
从
char
到 unsigned char
的转换总是产生“预期的”无符号字节值,然后可以将其转换为无符号整数。
关于c - C中赋值期间的隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623334/