Narrowing conversion

Viewed 4155
#include <iostream>
#include <vector>
#include <cctype>

using namespace std;

char get_selection() {
    char selection{};
    cin >> selection;
    return toupper(selection);
}

int main() {
    char selection {};
    do{
        selection = get_selection();
        switch(selection){
           ...
        }
    } while(selection!='Q');

    cout<<endl;
    return 0;
}

I'd like to know why I get this check/warning/tip

Clang-Tidy: Narrowing conversion from 'int' to signed type 'char' is implementation-defined

The only thing I am doing there is getting the char and "uppercasing" it, in case it's not already, so I don't have to handle 2 cases on my switches. Does anybody know what I'd have to change, in order to get rid of this, so I'd get it completely green, since this is the only issue? It seems like I lack some knowledge regarding conversion.

Thanks!

printscreen

2 Answers

In this function

char get_selection() {
    char selection{};
    cin >> selection;
    return toupper(selection);
}

the compiler makes implicit conversion from the type int, the return type of the C function toupper, to the type char.

To avoid the warning make explicit conversion for example like

char get_selection() {
    char selection{};
    cin >> selection;
    return char( ::toupper( ( unsigned char )selection) );
}

Another solution that doesn't rely on implementation-defined behaviour is:

return toupper(selection, std::locale());

This version of toupper returns the same type as the input.

Related