问题描述
我有一个使用gcc版本4.6.3的项目,我不得不使用-Wall -Werror -Wconversion进行编译。下面的简单示例显示了我无法摆脱的错误:
#include
int main(void){
uint32_t u = 0;
char c = 1;
u + = c;
return(int)u;
$ b用上面的标志编译它:
test.c:7:8:错误:从'char'转换为'uint32_t'可能会改变结果的符号[-Werror = sign-conversion]
好的,很好。只需添加一个类型转换,对吧?不。将第7行更改为 u + =(uint32_t)c 不会使错误消失。即使将它改为 u = u +(uint32_t)c 也不会让它消失。
是否有可能解决这个问题?
请注意,char来自一个字符串,所以我没有选择改变它的类型。 b $ b
解决方案这里编译得很好:
u + =(unsigned char)c;
然而,这只会使警告无效 - 不会对每个人执行任何操作在运行时 c ,与Basile的建议不同。
I have a project which uses gcc version 4.6.3, and I'm forced to compile with "-Wall -Werror -Wconversion". The following simple example shows an error I can't get rid of:
#include <stdint.h> int main(void) { uint32_t u = 0; char c = 1; u += c; return (int)u; }Compiling it with the above flags gives:
test.c:7:8: error: conversion to ‘uint32_t’ from ‘char’ may change the sign of the result [-Werror=sign-conversion]Ok, fine. Just add a typecast, right? Nope. Changing line 7 to u += (uint32_t)c does not make the error go away. Even changing it to u = u + (uint32_t)c does not make it go away.
Is it possible to fix this?
Please note that the "char" is coming from a string, so I don't have the option to change its type.
解决方案This compiles fine here:
u += (unsigned char)c;This will only silence the warning, however — without doing anything to each c at run-time, unlike Basile's proposal.
这篇关于C:如何摆脱转换错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!