转换从'诠释'为size_t“可能会改变结果的符号 - GCC,C [英] conversion to ‘size_t’ from ‘int’ may change the sign of the result - GCC , C
问题描述
在项目中,我打开警告视为错误,并使用 -pedantic
和 -ansi
标签编译。我使用的GCC编译器。在这个项目中,我不得不使用第三方源$ C $ C这已经得到了很多的警告。自从我把警告作为错误,我有固定在其code一个艰难的时间。
In my project I have turned on treat warnings as errors and compiling using the -pedantic
and -ansi
tags. I am using GCC compiler. In this project I have to use a third party source code which has got lot of warnings. Since I treat warnings as errors, I am having a tough time in fixing their code.
大部分的警告是关于从 INT
到为size_t
无效转换或反之亦然。在某些情况下,我不能够使这两个变量的类型相同,我的意思是我不能够改变的东西为size_t
。在这种情况下,我做一个明确的转换。喜欢的东西,
Most of the warnings are about invalid conversion from int
to size_t
or viceversa. In some cases, I won't be able to make both the variables same type, I mean I won't be able to change something to size_t
. In such cases I am doing an explicit cast. Something like,
size_t a = (size_t) atoi(val);
我想知道这是正确的做法?是否有投做着这样什么问题?
I am wondering is this the correct approach? Is there any problem in doing cast like this?
如果这些警告都是次要的,我可以燮preSS它只能在自己的文件?我该怎么做同样的MSVC?
If these warnings are minor, can I suppress it only on their files? How do I do the same on MSVC?
推荐答案
编辑:
铸造是唯一的方法,如果你想闭嘴每个实例编译器在便携式的方式。只要它是罚款,你知道你在做什么,例如就可以确保中的atoi
结果将永远是否定的。
Casting is the only approach if you want to shut up the compiler per instance in a portable way. It is fine as long as you know what you're doing, e.g. that you can ensure the result of atoi
will never be negative.
在GCC,你可以关闭与 -Wno符号转换
标记的所有符号转换的警告。还有 -Wno-sign-compare的
(对于东西像 2U> 1
),但它不会是相关除非你使用 -Wextra
。
In GCC, you can turn off all sign conversion warnings with the -Wno-sign-conversion
flag. There is also -Wno-sign-compare
(for stuff like 2u > 1
) but it won't be relevant unless you use -Wextra
.
您也可以使用诊断编译指示的像
#pragma GCC diagnostic ignored "-Wsign-conversion"
在MSVC,有相关的符号/无符号不匹配的,例如一些警告:
In MSVC, there are several warnings relevant to signed/unsigned mismatch, e.g.:
- 等级4:
- Level 4:
- C4389, C4245, C4365
- C4018 (
2U大于1
)
- C4018 (
2u > 1
)
- C4267 (
为size_t
→INT
)
- C4267 (
size_t
→int
)
要禁用MSVC的警告,你可以添加一个
的#pragma警告
例如To disable a warning in MSVC, you could add a
#pragma warning
e.g.#pragma warning (disable : 4267)
,或在编译器选项中添加
/ wd4267
标记。也许你应该使用
strtoul将
而不是中的atoi
。size_t a = strtoul(val, NULL, 0);
(没有警告的仅在的
为size_t
是大无符号长
。在大多数平台上,这是事实,但它不能保证。)(There is no warning only if
size_t
is as large asunsigned long
. On most platforms, this is true, but it is not guaranteed.)好处是,你可以使用此功能,例如执行错误检查。
The advantage is you could perform error checking with this function, e.g.
#include <stdlib.h> #include <stdio.h> int main () { char val[256]; fgets(val, 256, stdin); char* endptr; size_t a = strtoul(val, &endptr, 0); if (val == endptr) { printf("Not a number\n"); } else { printf("The value is %zu\n", a); } return 0; }
这篇关于转换从'诠释'为size_t“可能会改变结果的符号 - GCC,C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Level 4: