Pregunta

I am trying to rewrite the following piece of code:

$ cat t.c 
int main()
{
  unsigned int i = 0;
  int v = 3;
  i |= v;
  return 0;
}

Using a recent gcc you should get the following warning:

$ gcc -Wconversion t.c
t.c: In function ‘main’:
t.c:5:3: warning: conversion to ‘unsigned int’ from ‘int’ may change the sign of the result [-Wsign-conversion]

How should I rewrite the bitwise OR to avoid this warning while maintaining code readability. unsigned int i is something very deep in the library code, so I cannot change this to an int.

¿Fue útil?

Solución

You should't change from unsigned, but to it. Bitwise operations are always best performed on unsigned variables.

Make v unsigned!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top