简体   繁体   中英

Comparison between signed and unsigned integer expressions

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

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?

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

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

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

This line is the problem

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

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)

Or simply use a range-based for loop.

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

For (int i =0,i<sizeof ....) That line is the problem.The sizeof function returns an unsigned integer thus causing error when compared to the signed int. Try creating an int variable for the sizeof like this Int size=sizeof()... then replace in your line as follows For (int i=0,i<size...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM