不同编译器下的i++不尽相同。
代码
#include<iostream>
using namespace std;
int main(){
string s = "hello";
char str[20] = { 0 };
int i = 0;
str[i] = s[i++];
//str[i++] = s[i];
cout << "0 \t" << str[0] << endl;
cout << "1\t" << str[1] << endl;
int a[3] = { 3, 4, 5 };
int b[2] = { 0, 0 };
i = 0;
b[i] = a[i++];
//b[i++] = a[i];
cout << "0 \t" << b[0] << endl;
cout << "1\t" << b[1] << endl;
}
Ubuntu 18.04下
编译器版本:gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)
在gcc编译器下,无论是string类型还是int类型,无论是“str[i] = s[i++];“,“b[i] = a[i++];”执行结果都是b[0] = a[1],或str[0] = str[1]。即会在b[i] = a[i]之前执行i++。
而”str[i++] = str[i]”,“b[i++] = a[i];”执行结果都是b[0] = a[0],或str[0] = str[0]。即会在b[i] = a[i]之后执行i++。
执行结果:
str[i] = s[i++];
b[i] = a[i++];
执行结果:
str[i++] = str[i];
b[i++] = a[i];
Windows10下
编译器版本:MSVC Version: 1929
在MSVC编译器下,对于string类型,“str[i] = s[i++];“执行结果是str[0] = str[1]。即会在str[i] = str[i]之前执行i++。“str[i++] = str[i];”执行结果是str[0] = str[0]。即会在b[i] = a[i]之后执行i++。
而int类型无论是“b[i] = a[i++];”还是“b[i++] = a[i];”执行结果都是b[0] = a[0]。即会在b[i] = a[i]之后执行i++。
执行结果:
str[i] = s[i++];
b[i] = a[i++];
执行结果:
str[i++] = s[i];
b[i++] = a[i];
MSVC下的反汇编代码
可以看到在没有执行赋值操作之前就把i的值进行了加一的操作(add ecx,1)
可以看到在执行了赋值操作之后才把i的值加一(add eax,1)
建议
b[i++] = a[i]分开写:b[i] = a[i]; ++i;