C++一次输出调用多次++
创建字符串“876”,理想输出:876
错误代码:实际输出:678
s="876";
index=0;
cout<<s[index++]<<s[index++]<<s[index++];
正确代码:实际输出:876
s="876";
index=0;
//方法一:
cout << temp[index++];
cout << temp[index++];
cout << temp[index++];
//方法二:
cout << temp[index]<< temp[index+1]<< temp[index+2];
理想输出:876;实际输出:678
查找了一下原因,大概明白了是赋值先后的问题
其中原理可以参考这篇博客的示例https://blog.csdn.net/github_39329077/article/details/82820829
如这篇文章中示例
i= 1; a[++i] = a[++i] + a[++i] + 2;
输出的实际结果是a[4]=a[3]+a[4]+2;
在 cout<<s[index++]<<s[index++]<<s[index++]; 该语句的运行中,可以把式子当成两个s[index++]=s[index++](这里的等号只是便于理解符号前后的运算,不是真正的相等)
因为++在index之后,所以从后往前推。从后两个来看,等价于s[1]=s[0];前两个输出等价于s[2]=s[1];
因此输出语句等价于cout<<s[2]<<s[1]<<s[0];
                    
                
                
            
        
浙公网安备 33010602011771号