C: How to get rid of conversion error?

I have a project that uses gcc version 4.6.3, and I have to compile with "-Wall -Werror -Wconversion". The following simple example shows an error that I cannot get rid of:

#include <stdint.h> int main(void) { uint32_t u = 0; char c = 1; u += c; return (int)u; } 

Compiling 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] 

Good perfect. Just add a type, right? Nope. Changing line 7 to u += (uint32_t)c does not result in an error. Even changing it to u = u + (uint32_t)c does not make him leave.

Can this be fixed?

Note that "char" comes from a string, so I have no way to change its type.

+4
c gcc casting
Oct 19 '12 at 14:25
source share
3 answers

This compiles here:

 u += (unsigned char)c; 

This will only close the warning, however, without doing anything for each c at runtime, unlike the Basile clause.

+2
Oct. 19 '12 at 15:19
source share

The problem is with the signed (negative) character. You can try

  u += (unsigned) (c&0xff); 
+5
Oct 19 '12 at 14:30
source share

The question is what kind of conversion do you want. If you need a transformation defined by the standard, you probably need to assign c variable (temporary) uint32_t .

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

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

If this is not the intended conversion, but why are you then explicitly requesting it with (uint32_t)c ? - the solutions proposed by Bazile Starinkevich or Mikhail T., or the -funsigned-char flag would have excluded the warning.

IMO this is a (terrible) error in gcc, and clang seems to agree, u += (uint32_t)c; works as intended.

+1
Oct 19 '12 at 15:44
source share



All Articles