【发布时间】:2013-11-14 11:12:16
【问题描述】:
我有以下代码:
#include <stdlib.h>
#include <stdio.h>
void test(unsigned char * arg) { }
int main() {
char *pc = (char *) malloc(1);
unsigned char *pcu = (unsigned char *) malloc(1);
*pcu = *pc = -1; /* line 10 */
if (*pc == *pcu) puts("equal"); else puts("not equal"); /* line 12 */
pcu = pc; /* line 14 */
if (pcu == pc) { /* line 16 */
test(pc); /* line 18 */
}
return 0;
}
如果我用 gcc 版本 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 编译它(但不限于这个特定版本)和选项
gcc a.c -pedantic -Wall -Wextra -Wsign-conversion -Wno-unused-parameter; ./a.out
我收到以下警告
test.c: In function ‘main’:
test.c:10:21: warning: conversion to ‘unsigned char’ from ‘char’ may change the sign of the result [-Wsign-conversion]
test.c:14:13: warning: pointer targets in assignment differ in signedness [-Wpointer-sign]
test.c:16:17: warning: comparison of distinct pointer types lacks a cast [enabled by default]
test.c:18:17: warning: pointer targets in passing argument 1 of ‘test’ differ in signedness [-Wpointer-sign]
test.c:4:6: note: expected ‘unsigned char *’ but argument is of type ‘char *’
not equal
g++ 警告/错误类似。我希望我能理解为什么第 12 行的比较被评估为 false,但是在这种情况下有没有办法得到警告?如果不是,第 12 行和引起警告的行之间是否存在一些主要区别? char 和 unsigned char 的比较不应该得到警告有什么具体原因吗?因为至少乍一看,第 12 行在我看来比例如更“危险”。第 16 行。
一个简短的“背后故事”:我必须将来自不同来源的代码片段组合在一起。其中一些使用 char,一些使用 unsigned char。 -funsigned-char 可以正常工作,但我不得不避免它,而是添加正确的类型转换。这就是为什么这样的警告对我有用的原因,因为现在,如果我忘记在这种情况下添加类型转换,程序就会默默地失败。
提前致谢,P。
【问题讨论】:
-
有趣的是,如果我将
chars 更改为ints,它确实会发出警告。 -
@ams:我想区别在于
chars 的情况下char和unsigned char都转换为(signed)int。那么值是-1和255,它们有相同的类型(所以当时没有任何警告的理由),当然它们不相等。 -
是的,我刚刚写下了那个答案。 :)
标签: gcc