有符号和无符号整数表达式之间的比较 [英] Comparison between signed and unsigned integer expressions

查看:152
本文介绍了有符号和无符号整数表达式之间的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just started using OpenGL. This is my first code:

// 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行)。
我还尝试编写新代码,然后查看导致问题的原因:

The error I am getting is: Warning: comparison between signed and unsigned integer expressions (line 9). I also tried writing a new code then to see whats causing the problem:

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

此代码运行良好。为什么第一个代码不能正常工作?

This code works perfectly fine. Why is the first code not working fine?

编辑:
在Cyber​​的回答之后,我将循环更改为:

Following up on Cyber's annswer, I changed the loop to:

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

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

But the OpenGL code does not do the expected i.e. show "Hello, world!" message in the window. It just creates a window with "OpenGL hello program" written at the top and nothing else.

推荐答案

此行是问题

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

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

The operator sizeof has the return type of std::size_t which is therefore what you should use for the type of your variable i. std::size_t is an unsigned type, so the compiler is warning you that you are comparing a signed type (int) to an unsigned type, because the comparison is potentially unsafe if the value of one variable is not in the representable range of in the other type.

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

或直接使用基于范围的for循环。

Or simply use a range-based for loop.

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

这篇关于有符号和无符号整数表达式之间的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆