c - gcc - 使用 "-funsigned-char"仍然会导致 "-Wchar-subscripts"警告

标签 c gcc

这不是关于如何防止此警告的问题,而是关于为什么我收到警告的问题。

考虑以下程序:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    char *str = "Hello World!";
    int   len = strlen(str);

    // Yes, a char, bare with me
    char index = 6;
    char seek  = 'Z';

    // Reject the string if str[index] != seek
    // Include some bounds checks for safety
    if (index < 0 || index >= len || str[index] != seek) {
        puts("Rejected");

    } else {
        puts("Kept");
    }

    return 0;
}

如果您在启用所有警告的情况下编译它,您会得到以下信息:

$ gcc -Wall -Wextra char.c -o char
char.c: In function ‘main’:
char.c:15:5: warning: array subscript has type ‘char’ [-Wchar-subscripts]
     if (index < 0 || index >= len || str[index] != seek) {
     ^

很好!默认情况下,char可以有符号并包含负值,所以 str[index]如果 index 可能会导致问题是负的。

如果我们强制所有 char 会怎么样? s 与 -funsigned-char 未签名?
这将保证它们永远不会为负,并且应该可以防止警告。

$ gcc -Wall -Wextra -funsigned-char char.c -o char
char.c: In function ‘main’:
char.c:15:15: warning: comparison is always false due to limited range of data type [-Wtype-limits]
     if (index < 0 || index >= len || str[index] != seek) {
               ^
char.c:15:5: warning: array subscript has type ‘char’ [-Wchar-subscripts]
     if (index < 0 || index >= len || str[index] != seek) {
     ^

gcc似乎意识到 index < 0永远是错误的,因为 index未签名。这解释了第一个警告。
但是,它仍然警告 str[index]即使它知道 index永远不会是负面的。

为什么 gcc当它已经知道它永远不会为负时,仍然会警告 char 索引?

最佳答案

-Wchar-subscripts 旨在作为可移植性警告。它告诉您在一般情况下 char 可以被签名。在您的情况下它未签名的事实无关紧要。如果您不关心一般情况 - 禁用警告。

请注意,例如,您不会收到有关 int 下标的警告,即使 int 可以为负数。当您使用 int 作为下标时,编译器假定您知道自己在做什么。但是对于 char 它想要警告。

另请注意,如果您在代码中明确使用 signed char 作为下标,则警告将消失,即使 signed char 肯定可以为负数。编译器再次假定您知道自己在做什么。

关于c - gcc - 使用 "-funsigned-char"仍然会导致 "-Wchar-subscripts"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36185782/

相关文章:

c - 快速访问 C 结构

c - 我是否正确创建了协议(protocol)?

c - 在C中打开文件如何防止读取错误的数据类型

c++ - 交叉编译 gcc

c - 字符串说明符( %d 、 %f 等...)

c - delwin(),endwin(),不在条件语句内工作

c++ - 编译器重新排序与内存重新排序

gcc - 为什么 `-finstrument-functions` 对我不起作用?

linux - 在 Linux-PowerPC 上使用 GCC 连接到 DB2/400

c - 减少 C 程序的大小以适应 qr 代码