Search code examples
c++cgccwarnings

warning: conversion to 'unsigned char' from 'int' may alter its value


The code is:

*(buf+2) |= (unsigned char)(mFlag & 0x7f);

buf is unsigned char * and mFlag is unsigned char

I guess it is because the return value of operator|= so that I get the warnings

warning: conversion to 'unsigned char' from 'int' may alter its value

How can I remove the warning? Is it due to operator|=?


Solution

  • In C all arithmetic (including &) is done in types at least as wide as int. So the result of your expression will always be int or unsigned depending on the type of your constant.

    Since the constant 0x7f is obviously within bounds for any of the character types the warning your compiler gives is in effect not really helpful, I would even consider it a bug.

    The only thing that you can do about this is

    *(buf+2) = (unsigned)*(buf+2) | 0x7FU; 
    

    That is to convert the value explicitly to the wider type. If this still gives you a warning for the assignenent use

    *(buf+2) = (unsigned char)((unsigned)*(buf+2) | 0x7FU);
    

    but then you should definitively think of upgrading your compiler or change the warning options that you use.