Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: How to get rid of conversion error?

Tags:

c

casting

gcc

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.

like image 464
brooks94 Avatar asked Feb 19 '23 19:02

brooks94


2 Answers

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

 u += (unsigned) (c&0xff);
like image 81
Basile Starynkevitch Avatar answered Feb 27 '23 18:02

Basile Starynkevitch


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.

like image 26
Mikhail T. Avatar answered Feb 27 '23 16:02

Mikhail T.