c++ - 有符号和无符号整数表达式之间的比较

标签 c++ compiler-errors

我刚开始使用 OpenGL。这是我的第一个代码:

// OpenGL hello program
#include<iostream>
#include <GL/glut.h>
#include <cstring>

void display() {
    glClear(GL_COLOR_BUFFER_BIT);
    char message[] = "Hello, world!";
    glRasterPos2d(0, 0);
    for (int i = 0; i < sizeof(message) / sizeof(message[0]); i++)
    {
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, message[i]);
    }
}

int main(int argc, char *argv[]) {
    glutInit(&argc, argv);
    glutInitWindowSize(500, 500);
    glutCreateWindow("OpenGL hello program");
    glutDisplayFunc(display);
    glutMainLoop();
}

我得到的错误是:警告:有符号和无符号整数表达式之间的比较(第 9 行)。 我还尝试编写新代码,然后查看导致问题的原因:

#include<iostream>
#include <cstring>

void display1() {
    char message[] = "Hello, world!";

    for (int i = 0; i < sizeof(message) / sizeof(message[0]); i++)
        std::cout<<message[i];
}

int main() {
    display1();
}

这段代码工作得很好。为什么第一个代码不能正常工作?

编辑: 根据 Cyber​​ 的回答,我将循环更改为:

for (unsigned int i = 0; i < sizeof(message) / sizeof(message[0]); i++)

但是 OpenGL 代码没有达到预期效果,即显示“Hello, world!”窗口中的消息。它只是创建一个窗口,顶部写有“OpenGL hello 程序”,没有其他内容。

最佳答案

这一行就是问题所在

for (int i = 0; i < sizeof(message) / sizeof(message[0]); i++)

运营商sizeof返回类型为 std::size_t因此,您应该将其用于变量 i 的类型。 std::size_t 是无符号类型,因此编译器警告您正在将有符号类型 (int) 与无符号类型进行比较,因为比较可能不安全如果一个变量的值不在另一种类型的可表示范围内。

for (std::size_t i = 0; i < sizeof(message) / sizeof(message[0]); ++i)

或者简单地使用基于范围的 for 循环。

for (auto i : message)
{
    std::cout << i;    // i is a char from the message array
}

关于c++ - 有符号和无符号整数表达式之间的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25429771/

相关文章:

c++ - 如何初始化模态对话框? (C++/MFC)

c++ - 我的 try catch 零除法有问题吗?

android - 没有错误,但应用程序无法正常工作。按钮不起作用

有关 SQLException 和 RemoteException 的 Java 编译错误

c++ - 无法使用我的 QAbstractItemModel 派生类让 QColumnView 显示多行数据

C++ - 模板类对象数组

c++ - 如何使用 CMake 测试 C++ 应用程序没有内存错误?

compiler-errors - Elixir - 无法在比赛中调用远程功能

f# - 编译错误提示值不是函数

Java 包无法编译