c++ - 为什么编译器允许用户更改 'auto' 变量的类型?

我希望 auto 关键字一次从初始化程序中推断出变量的类型,并在整个代码中保持该类型。令我惊讶的是,我的编译器 (g++ 9.3.0) 允许我更改它的类型并且它仍然有效。当我首先将变量用作 int 然后用作 float 时,这对我来说是可以接受的。但是,当我使用 auto 关键字声明一个字符串,然后为该变量分配一个浮点值时,编译器不会抛出错误,但也不会在浮点赋值后打印值。有人可以解释为什么它首先允许将浮点值分配给字符串变量吗?编译器是否每次都接受新的分配?或者它会抛出某种我无法捕获的异常吗?下面的代码-

#include <iostream>

int main()
{
 auto x = '2';
 
 std::cout << x << std::endl;
 
 x = 3.0; // Why is this allowed?
 
 std::cout << x << std::endl; // This won't print
 
 return 0;
}

最佳答案

为了向您展示发生了什么,我通过一些编译时类型检查扩展了示例:

#include <type_traits>
#include <iostream>

int main()
{
    auto x = '2';

    // decltype(x) is the type for variable x
    // compare it at compile time with char type
    static_assert(std::is_same_v<decltype(x), char>);

    std::cout << x << std::endl;

    x = 3.0; // Why is this allowed? because it does a narrowing conversion from double to char
    // my compiler even gives this warning :
    // main.cpp(11,6): warning C4244: '=': conversion from 'double' to 'char', possible loss of data
    
    // type of x is still the same and it is still a char
    static_assert(std::is_same_v<decltype(x), char>);

    std::cout << static_cast<int>(x) << std::endl; // the cast is here to be able to print the actual value of the char

    return 0;
}

关于c++ - 为什么编译器允许用户更改 'auto' 变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70518606/

相关文章:

r - 在 R 中查找汇总列的相对频率

c# - Entity Framework 排序列表

() takes ">python - 为什么在我给出位置参数时 lambda 返回 "() takes

haskell - 如何为自定义数据类型定义 (+) 函数?

javascript - 一键执行两个功能

c++ - 使用 C++ 生成真正的随机数 (Windows 10 x64)

python - 打印 RGB 背景

node.js - 带有 Webpack 的 Electron 原生 NodeJS 模块

c++ - 即使在手动设置显示环境变量后,WSL Ubuntu 仍显示 "Error: Unable

r - 是否可以将变量从全局环境移动到单独的环境中?