C: How to get rid of conversion error?

喜夏-厌秋 提交于 2019-12-12 11:24:21

问题


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.


回答1:


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.




回答2:


The issue is with signed (negative) character. You might try

 u += (unsigned) (c&0xff);



回答3:


The question is which conversion you want. If you want the conversion defined by the standard, you apparently need to assign c to a (temporary) uint32_t variable.

uint32_t temp = (uint32_t)c;
u += temp;

works as intended (at least with my gcc-4.6.2).

If that is not the intended conversion - but why would you then explicitly ask for it using (uint32_t)c? - the solutions suggested by Basile Starynkevich or Mikhail T., or the -funsigned-char flag would eliminate the warning.

IMO it's a (terrible) bug in gcc, and clang seems to agree, u += (uint32_t)c; works as intended there.



来源:https://stackoverflow.com/questions/12976343/c-how-to-get-rid-of-conversion-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!