Search code examples
c++gcctype-conversioncompiler-warningssuppress-warnings

Trying to fix conversion warning


I am getting the following error:

warning: conversion to ‘short unsigned int’ from ‘int’ may alter its value [-Wconversion]

for the method

template<typename T> bool get_int(FILE* IN, T* val) {
    T rc = 0;
    for (size_t i = 0; i < sizeof(T) << 3; i += 8) {
        int temp = getc(IN);
        if (temp == EOF)
            return false;
        rc |= (T)temp << i;
    }
    *val = rc;
    return true;
}

when I have the lines

unsigned short foo;
get_int<unsigned short>(IN, &foo);

How can I get rid of this GCC warning?


Solution

  • Try this:

    rc |= (T)(temp << i);
    

    (T)temp is promoted to int again for the bitwise shift.