C++ C++;microsoft visual studio 2015中指针算法的不合理结果

C++ C++;microsoft visual studio 2015中指针算法的不合理结果,c++,visual-studio,pointer-arithmetic,C++,Visual Studio,Pointer Arithmetic,我在指针算术中发现了一个非常有趣的现象。我正在使用microsoft visual studio 2015 我有以下程序 #include<iostream> using namespace std; void testFunction2(const char *s, int n) { unsigned int x; for (x = n - 1; x >= 0; --x) cout << *(s + x); } int main()

我在指针算术中发现了一个非常有趣的现象。我正在使用microsoft visual studio 2015
我有以下程序

#include<iostream>
using namespace std;
void testFunction2(const char *s, int n)
{
    unsigned int x;
    for (x = n - 1; x >= 0; --x)
        cout << *(s + x);
}
int main()
{
    char str[80] = "string";
    testFunction2(s, strlen(s));
}
#包括
使用名称空间std;
void testFunction2(常量字符*s,整数n)
{
无符号整数x;
对于(x=n-1;x>=0;--x)
cout=0
x>=1
。 它将按预期打印“gnirt”。

我还尝试了类似
cout的代码,并显示了警告,您将看到以下内容:

warning: comparison of unsigned expression >= 0 is always true [-Wtype-limits]
您将
x
声明为
unsigned int
。然后比较
x>=0
。由于
x
是无符号的,因此这总是正确的。当
x
减至0以下时,该值会环绕到
UINT\u MAX
。然后使用该值对数组进行索引,这是方式/strong>越界。此调用是的


x
的类型更改为
int
以允许其具有负值,这样比较将是有效的。

您是否意识到将
无符号
与0进行比较意味着什么?这是因为您使用了无符号的int。因此它不能小于0。当您尝试减少已为零的无符号int时,它会下溢d循环回到最大值。g++:`警告:无符号表达式的比较>=0总是正确的`基本上不要对任何东西使用无符号,除非你真的需要使用它。我想它会自己转换为绝对值,即,
unsigned int x=-1
,然后x将是1,我测试了它,我错了。谢谢你的帮助我有一个级别3警告(/W3),但它不会发出任何警告