[英]No warning with conversion to int from size_t
Consider this program: 考虑以下程序:
#include <stdio.h>
int main() {
int xr = 2;
int ya = 3;
size_t zu = 4;
xr = zu;
xr = (size_t) ya;
xr = sizeof ya;
return xr;
}
Compiling yields a warning: 编译会产生警告:
conversion to ‘int’ from ‘size_t’ may alter its value [-Wconversion]
xr = zu;
^
but only this warning. 但只有这个警告。 As size_t
and sizeof
both return unsigned data types, I would expect to see 3 warnings. 由于size_t
和sizeof
都返回无符号数据类型,因此我希望看到3条警告。 What is going on here? 这里发生了什么?
cast and sizeof are C operators , not functions. cast和sizeof是C运算符 ,而不是函数。 If you use this example: 如果使用此示例:
#include <stdint.h>
size_t mik() {
return 1;
}
int main() {
return mik();
}
You get a warning as expected: 您会收到预期的警告:
conversion to ‘int’ from ‘size_t’ may alter its value [-Wconversion]
return mik();
^
being operators, the only warnings you can expect are overflow: 作为操作员,您可以期望的唯一警告是溢出:
char nov[UINT16_MAX];
// large integer implicitly truncated to unsigned type [-Woverflow]
uint8_t osc = sizeof nov;
or improper use of cast: 或不当使用演员表:
uint32_t nov = 1;
// conversion to ‘uint32_t’ from ‘int’ may
// change the sign of the result [-Wsign-conversion]
uint32_t osc = (int32_t) nov;
// conversion to ‘uint8_t’ from ‘short unsigned int’ may alter its value [-Wconversion]
uint8_t pap = (uint16_t) nov;
now improper use of cast is actually what was done in the question too: 现在,不正确地使用强制类型转换实际上也是问题所在:
xr = (size_t) ya;
Here is the difference : 区别在于 :
if the target type is signed, the behavior is implementation-defined (which may include raising a signal) 如果目标类型已签名,则行为是实现定义的(可能包括发出信号)
I would say the compiler is smart enough. 我会说编译器足够聪明。 Consider the below program : 考虑下面的程序:
int xr = -2;
int ya = -3;
size_t zu = 4;
xr = zu;
zu = ya;
/* Added test case
* A negative 'ya' when converted to size_t should change its value.
*/
printf("zu : %zu , but is this what you expected\n",zu);
xr = (size_t) ya;
xr = sizeof ya;
Compilation gives : 编译给出:
gcc -Wall -Wconversion 38257604.c -o 38257604
38257604.c: In function ‘main’:
38257604.c:11:3: warning: conversion to ‘int’ from ‘size_t’ may alter its value [-Wconversion]
xr = zu;
^
38257604.c:12:3: warning: conversion to ‘size_t’ from ‘int’ may change the sign of the result [-Wsign-conversion]
zu = ya;
^
38257604.c:8:7: warning: variable ‘xr’ set but not used [-Wunused-but-set-variable]
int xr = -2;
^
Moral 道德
in C, you're given the responsibility of type-checking. 在C语言中,您有责任进行类型检查。 So better take heed of 所以最好注意
-Wsign-conversion
is not enabled by default. 默认编译器标志,例如-Wsign-conversion
默认情况下未启用。 when you write statements involving type conversions. 当您编写涉及类型转换的语句时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.