gpt4 book ai didi

c++ - 自动将int转换为unsigned int

转载 作者:行者123 更新时间:2023-12-02 10:00:30 25 4
gpt4 key购买 nike

#include <iostream>
using namespace std;

int main() {
unsigned int u = 5;
int x = -1;
if(x>u) {
cout<<"Should not happen"<<endl;
} else {
cout<<"Ok"<<endl;
}
}
此代码输出 Should not happen。在将字符串的大小(size_t是无符号的int或无符号的long long值)与int进行比较时遇到了这个问题。
似乎C类型将int转换为unsigned int,但实际上,它似乎会带来错误。老实说,鉴于int与unsigned int的不兼容程度,我宁愿选择编译时错误。我想知道为什么这样的约定?

最佳答案

您可以在Clang中启用-Wsign-compare -Werror:Try it online!
它将产生一个编译时错误(因为-Werror将警告视为错误):

.code.tio.cpp:7:9: error: comparison of integers of different signs: 'int' and 'unsigned int' [-Werror,-Wsign-compare]
if(x>u) {
~^~
1 error generated.
出于某种原因,Clang中的 -Wall -Werror(但在GCC中不是)不会产生任何错误。但是 -Wall -Wextra -Werror确实包含 -Wsign-compare,因此您可以使用它。

关于c++ - 自动将int转换为unsigned int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62728368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com