最近整理了下代码警告问题。这里记录一下。
在以前某个项目上竟然用-w把gcc的警告给关闭了,怪不得编译代码完全没警告,多漂亮的代码!
未使用变量、未使用函数返回值, 未使用变量:
1 | warning: unused variable ‘ret’ [-Wunused-variable] |
–>修改:删之。
没有达到函数末尾:
1 | warning: control reaches end of non-void function [-Wreturn-type] |
没有返回值:
1 | warning: no return statement in function returning non-void [-Wreturn-type] |
–> 修改:加上返回值
参数一致性,参数类型检查
空字符串:
1 | warning: zero-length gnu_printf format string [-Wformat-zero-length] |
类型不对:
1 | warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘char*’ [-Wformat=] |
–> 修改:按printf格式来修改,unsigned long使用%lu。不要用%d来打印字符串指针。
有符号和无符号:
1 | warning: pointer targets in passing argument 2 of ‘ll_foobar’ differ in signedness [-Wpointer-sign] |
有符号和无符号比较:
1 | warning: comparison between signed and unsigned integer expressions [-Wsign-compare] |
–> 修改:强制转换类型
参数类型:
1 | warning: passing NULL to non-pointer argument 2 of ‘void* memset(void*, int, size_t)’ [-Wconversion-null] |
–> 修改:用0来代替,或将NULL强转为INT。
比较诡异:
1 | warning: argument to ‘sizeof’ in ‘char* strncpy(char*, const char*, size_t)’ call is the same expression as the destination; did you mean to provide an explicit length? [-Wsizeof-pointer-memaccess] |
用意本身是好的,用法却是错的,ptr是指针,sizeof指针只能得到4。
类似的有:
1 | warning: argument to ‘sizeof’ in ‘void* memset(void*, int, size_t)’ call is the same expression as the destination; did you mean to dereference it? [-Wsizeof-pointer-memaccess] |
–> 修改:strncpy、memset第三个参数按实际给数值。
C++类构造函数初始化顺序问题:
1 | warning: CFoobar::m_nInit will be initialized after [-Wreorder] |
–> 修改:按声明的顺序排列。
常量字符串:
1 | warning: deprecated conversion from string constant to ‘CHAR* {aka char*}’ [-Wwrite-strings] |
–> 修改:字符串要加const。
打印格式化
1 | warning: too few arguments for format |
如本身要打印2个参数,但只有一个%。myprintf("hello world %d!\n", count, getname());
–>修改:认真检查参数。
4、类型一致性,类型转换
整数溢出:
1 | warning: integer overflow in expression [-Woverflow] |
转换转换:
1 | warning: narrowing conversion of ‘height’ from ‘DWORD {aka unsigned int}’ to ‘int’ inside { } is ill-formed in C++11 [-Wnarrowing] |
my_dst_size类型为int,但width和height为DWORD
–>修改:强制转换类型,保持一致。
1 | warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default] |
my_pos.pos为坐标。
–>修改:一一赋值。
1 | my_pos.pos.x = 0; |
括号、优先级
1 | warning: suggest parentheses around arithmetic in operand of '^' [-Wparentheses] |
–> 添加括号
1 | #define HELLO ((((z>>51)^(y<<32))+((y>>23)^(z<<5)))^((sum^y)+(k[(p&7)^e]^z))) |
另一个例子:
1 | warning: suggest parentheses around ‘&&’ within ‘||’ [-Wparentheses] |
switch
1 | warning: enumeration value ‘LL_FOO’ not handled in switch [-Wswitch] |
–>枚举类型没有完全使用,如没有default语句。添加之
地址总为真
1 | warning: the address of ‘filename’ will always evaluate as ‘true’ [-Waddress] |
其它
1 | error: function declaration isn’t a prototype |
–>函数声明如无参数,要加上void
李迟 2015.4.22周三中午