C++ 有符号和无符号整数表达式之间的比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25429771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparison between signed and unsigned integer expressions
提问by Bosnia
I just started using OpenGL. This is my first code:
我刚开始使用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();
}
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:
我得到的错误是:警告:有符号和无符号整数表达式之间的比较(第 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();
}
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 OpenGLcode 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.
但是OpenGL代码并没有像预期的那样显示“你好,世界!” 窗口中的消息。它只是创建了一个窗口,上面写着“OpenGL hello 程序”,没有别的。
回答by Cory Kramer
This line is the problem
这条线是问题
for (int i = 0; i < sizeof(message) / sizeof(message[0]); i++)
The operator sizeofhas the return type of std::size_twhich is therefore what you should use for the type of your variable i. std::size_tis 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.
运算符sizeof具有返回类型,std::size_t因此您应该将其用于变量类型i。std::size_t是无符号类型,因此编译器警告您正在将有符号类型 ( int) 与无符号类型进行比较,因为如果一个变量的值不在另一种类型的可表示范围内,则比较可能不安全。
for (std::size_t i = 0; i < sizeof(message) / sizeof(message[0]); ++i)
Or simply use a range-based for loop.
或者简单地使用基于范围的 for 循环。
for (auto i : message)
{
std::cout << i; // i is a char from the message array
}

