c++ - 缩小转换范围

标签 c++ integer implicit-conversion narrowing

#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;
}

我想知道为什么我会收到此检查/警告/提示

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

我在那里做的唯一一件事就是获取字符并将其“大写”,以防万一它还没有,所以我不必在交换机上处理两种情况。 有谁知道我必须改变什么,才能摆脱这个问题,所以我会把它完全变成绿色,因为这是唯一的问题? 看来我缺乏一些关于转换的知识。

谢谢!

printscreen

最佳答案

在这个函数中

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

编译器将 C 函数 toupper 的返回类型 int 隐式转换为 char 类型。

为了避免警告,请进行显式转换,例如

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

关于c++ - 缩小转换范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60912937/

相关文章:

c++ - 使用 autotools 为共享库正确安装 config.h

java - 理解 Java Integer.parseInt(String s, int radix) 源代码

c++ - 如何将二进制数据转换为整数值

c++ - VS 2010 C++ - 转换错误

c++ - 为什么无法通过 Call-by-Value 将 mutex 传递给 function?

c++ - 向 PDF 添加 FreeText 注释

string - 戈兰 : how to sum an array of integers as strings and numbers

c++ - 函数参数到子类c++的转换

c# - c# 编译器是否会执行多个隐式转换以从一种类型转换为另一种类型?

C++ MySQL 连接器库运行时错误