从'int'转换为'size_t'可能会改变结果的符号 - GCC,C

Nav*_*K N 4 c gcc warnings visual-c++

在我的项目中,我已将警告视为错误,并使用-pedantic-ansi标签进行编译.我正在使用GCC编译器.在这个项目中,我必须使用第三方源代码,它有很多警告.由于我将警告视为错误,因此我在修复代码时遇到了困难.

大部分的警告是关于从无效转换intsize_t或反之亦然.在某些情况下,我将无法使两个变量同类型,我的意思是我将无法改变某些东西size_t.在这种情况下,我正在做一个明确的演员.就像是,

size_t a = (size_t) atoi(val);
Run Code Online (Sandbox Code Playgroud)

我想知道这是正确的方法吗?像这样做演员有什么问题吗?

如果这些警告很小,我可以仅在其文件中禁止它吗?我如何在MSVC上做同样的事情?

ken*_*ytm 7

编辑:

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.

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.

You could also use the diagnostic pragmas like

#pragma GCC diagnostic ignored "-Wsign-conversion"
Run Code Online (Sandbox Code Playgroud)

In MSVC, there are several warnings relevant to signed/unsigned mismatch, e.g.:

To disable a warning in MSVC, you could add a #pragma warning e.g.

#pragma warning (disable : 4267)
Run Code Online (Sandbox Code Playgroud)

or add a /wd4267 flag in the compiler options.


Perhaps you should use strtoul instead of atoi.

size_t a = strtoul(val, NULL, 0);
Run Code Online (Sandbox Code Playgroud)

(There is no warning only if size_t is as large as unsigned 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;
}
Run Code Online (Sandbox Code Playgroud)


Mah*_*dsi 4

查看 OpenOffice wiki,了解无错误代码的最佳实践:http://wiki.services.openoffice.org/wiki/Writing_warning-free_code

他们建议对这些转换进行静态转换,然后提供一个编译指示来禁用特定代码部分的警告。

  • 谢谢。我使用的是 C 而不是 C++。`static_cast` 不可用。 (2认同)