Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Narrowing conversion

#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

like image 887
Kelv Avatar asked Nov 28 '25 00:11

Kelv


1 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) );
}
like image 64
Vlad from Moscow Avatar answered Nov 30 '25 14:11

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!