gpt4 book ai didi

c++ - 我不明白为什么我会收到有关有符号和无符号之间转换的警告,我的编译器错了吗?

转载 作者:行者123 更新时间:2023-12-03 10:05:09 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





gcc size_t and sizeof arithmetic conversion to int

(2 个回答)


10 个月前关闭。




我有这个代码:

#include <cstdint>
#include <deque>
#include <iostream>

int main()
{
std::deque<uint8_t> receivedBytes;
int nbExpectedBytes = 1;

if (receivedBytes.size() >= static_cast<size_t>(nbExpectedBytes))
{
std::cout << "here" << std::endl;
}
return 0;
}
使用 -Wsign-conversion,这在我的 linux 笔记本电脑上编译时不会发出警告,但在要运行的嵌入式 linux 上,我收到以下警告:

temp.cpp: In function ‘int main()’: temp.cpp:10:33: warning:conversion to ‘std::deque::size_type {aka long unsignedint}’ from ‘int’ may change the sign of the result [-Wsign-conversion]

 if (receivedBytes.size() >= static_cast<size_t>(nbExpectedBytes))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我就是不明白:
  • 我在我的 linux 笔记本电脑和嵌入式 linux 上都启用了 -Wsign-conversion,那么为什么我只在嵌入式 linux 上收到警告?
  • 我明确地从 int 转换至 size_t (由于强制转换是明确的,因此不应产生警告),然后比较 size_tstd::deque<unsigned char>::size_type ,那么触发警告的从有符号到无符号的隐式转换在哪里??!

  • 我不禁认为嵌入式linux上的编译器在这里是错误的。我错过了什么吗?
    编辑:在我的 linux 笔记本电脑上,我使用的是 g++ 9.3.0 版,而在嵌入式 linux 上,我使用的是 g++ 6.3.0 版(可能不是通常的二进制文件,因为它是 ARM64 架构)

    最佳答案

    这无疑是嵌入式编译器中的错误/错误。分离 static_cast来自 >=比较消除了警告,从在 Compiler Explorer 上测试以下代码可以看出, 选择了 ARM64 gcc 6.3.0 (linux):

    #include <deque>
    #include <cstddef>
    #include <cstdint>

    int main()
    {
    std::deque<uint8_t> receivedBytes;
    int nbExpectedBytes = 1;

    // Warning generated ...
    while (receivedBytes.size() >= static_cast<size_t>(nbExpectedBytes))
    {
    break;
    }

    // Warning NOT generated ...
    size_t blob = static_cast<size_t>(nbExpectedBytes);
    while (receivedBytes.size() >= blob)
    {
    break;
    }
    return 0;
    }
    此外,更改为(32 位)ARM gcc 6.3.0 (linux) 编译器时,警告也会消失。

    关于c++ - 我不明白为什么我会收到有关有符号和无符号之间转换的警告,我的编译器错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65020449/

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