使用三元运算符将 char 分配给 char 时如何通过转换避免(潜在)错误
How to avoid the (potential) error by conversion when assigning a char to a char with ternary operator
我有以下代码:
void foo(char* char_ptr, unsigned short len) {
char c = len != 0 ? char_ptr[0] : '[=10=]';
printf("%c", c);
}
我收到以下警告:
Clang-Tidy: Narrowing conversion from 'int' to signed type 'char' is implementation-defined
这东西说的是什么转换?我到处只有 char
s。我怎样才能避免这个(潜在的)错误?
这看起来像是“有一些隐含的魔法在发生,你只需要知道”的另一个例子。有没有一个地方可以让我查找 c 编译器隐式执行的所有魔法?
解释来自 this cppreference page 的信息,特别是在“条件运算符”部分,第 (3) 和 (1) 小节中,我们看到:
(3) Performs a conversion from the result of the evaluation to the
common type, defined as follows:
(1) if the expressions have arithmetic
type, the common type is the type after usual arithmetic conversions
然后,查看链接的“通常算术转换”,我们看到:
(4) Otherwise, both operands are integers. Both operands undergo
integer promotions (see below); then, ...
那些 整数提升 将导致 both 表达式被提升为 int
类型 - 即使您显式转换第二个, 如 char c = len != 0 ? char_ptr[0] : (char)'[=12=]';
.
因此,为了消除警告,需要将条件表达式(将是 int
类型)的 result 转换为 char
,如:
char c = (char)(len != 0 ? char_ptr[0] : '[=10=]');
6.5.15 Conditional Operator
...
5 If both the second and third operands have arithmetic type, the result type that would be determined by the
usual arithmetic conversions, were they applied to those two operands,
is the type of the result.
这似乎证实了 cppreference.com 提供的信息。
我有以下代码:
void foo(char* char_ptr, unsigned short len) {
char c = len != 0 ? char_ptr[0] : '[=10=]';
printf("%c", c);
}
我收到以下警告:
Clang-Tidy: Narrowing conversion from 'int' to signed type 'char' is implementation-defined
这东西说的是什么转换?我到处只有 char
s。我怎样才能避免这个(潜在的)错误?
这看起来像是“有一些隐含的魔法在发生,你只需要知道”的另一个例子。有没有一个地方可以让我查找 c 编译器隐式执行的所有魔法?
解释来自 this cppreference page 的信息,特别是在“条件运算符”部分,第 (3) 和 (1) 小节中,我们看到:
(3) Performs a conversion from the result of the evaluation to the common type, defined as follows:
(1) if the expressions have arithmetic type, the common type is the type after usual arithmetic conversions
然后,查看链接的“通常算术转换”,我们看到:
(4) Otherwise, both operands are integers. Both operands undergo integer promotions (see below); then, ...
那些 整数提升 将导致 both 表达式被提升为 int
类型 - 即使您显式转换第二个, 如 char c = len != 0 ? char_ptr[0] : (char)'[=12=]';
.
因此,为了消除警告,需要将条件表达式(将是 int
类型)的 result 转换为 char
,如:
char c = (char)(len != 0 ? char_ptr[0] : '[=10=]');
6.5.15 Conditional Operator
...
5 If both the second and third operands have arithmetic type, the result type that would be determined by the usual arithmetic conversions, were they applied to those two operands, is the type of the result.
这似乎证实了 cppreference.com 提供的信息。