對於c++中的i++與++i的分析

對於c++中的i++與++i的分析


最近看到兩篇文章,文章均是針對Java的編譯說明,對於c++我測試了一下實際有區別,相關題目我copy過來打算查源碼解讀一下原因。

  1. 面試官:你說你懂i++跟++i的區別,那你會做下面這道題嗎?
  2. 最通俗易懂的i++和++i詳解

環境

IDE: MSVC 2017

Hardware: Intel CPU

OS: win10 64bit

題目

示例1

int i = 0;
i = i++; 
System.out.println("i = " + i); 

示例2

int a = 2; 
int b = (3 * a++) + a;
System.out.println(b);

示例3

int a = 2; 
int b = a + (3 * a++);
System.out.println(b);

示例4

int i = 1;
int j = 1;
int k = i++ + ++i + ++j + j++; 
System.out.println(k);

示例5

int a = 0;
int b = 0;
a = a++;
b = a++;
System.out.println("a = " + a + ", b = " + b);

代碼

TestCase::TestCase()
{
	example1();
	example2();
	example3();
	example4();
	example5();
}


TestCase::~TestCase()
{
}

void TestCase::example1()
{
	std::cout << "example1" << std::endl;
	int i = 0;
	i = i++;
	std::cout << "i = " << i << std::endl;
}

void TestCase::example2()
{
	std::cout << "example2" << std::endl;
	int a = 2;
	int b = (3 * a++) + a;
	std::cout << "a = " << a << ", b = " << b << std::endl;
}

void TestCase::example3()
{
	std::cout << "example3" << std::endl;
	int a = 2;
	int b = a + (3 * a++);
	std::cout << "a = " << a << ", b = " << b << std::endl;
}

void TestCase::example4()
{
	std::cout << "example4" << std::endl;
	int i = 1;
	int j = 1;
	int k = i++ + ++i + ++j + j++;
	std::cout << "i = " << i << ", j = " << j << ", k = " << k << std::endl;
}

void TestCase::example5()
{
	std::cout << "example5" << std::endl;
	int a = 0;
	int b = 0;
	a = a++;
	b = a++;
	std::cout << "a = " << a << ", b = " << b << std::endl;
}

運行結果

在這裏插入圖片描述

分析

由於上網稍微查了下並沒有搜到官方詳細的說明,只有下邊這份來自微軟官網的 例子和簡單說明,但是感覺並沒有很大價值。1

// expre_Postfix_Increment_and_Decrement_Operators.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

int main() {
   int i = 10;
   cout << i++ << endl;
   cout << i << endl;
}

It is important to note that a postfix increment or decrement expression evaluates to the value of the expression prior to application of the respective operator. The increment or decrement operation occurs after the operand is evaluated. This issue arises only when the postfix increment or decrement operation occurs in the context of a larger expression.

//上邊說的情況我也有點不太懂,有大神明白請給與指教

例子1:

根據這個例子其實可以初步看出實現的順序,結果是i = 1說明在i = i++時是先處理i = i之後處理i++我們跟着這個思路看下一個例子。

例子2:

int b = (3 * a++) + a;可以通過這個例子看出來a++是括號完成後執行還是整行完成後執行。

結果b = 8說明b = (3 * 2) + 2a = 3說明在執行完b的計算後,進行了a++的操作這時a = 2 + 1

例子3:

這個例子與例子2是相同的,均可以看出來a++是括號完成後執行還是整行完成後執行。

結果b = 8說明b = 2 + (3 * 2)a = 3說明在執行完b的計算後,才進行a++的操作a = 2 +1

例子4:

這個例子就比較有意思了,可以從裏邊看到很多不同的東西,最終的結果是

// i = 3 j = 3 k = 8

i = 3j = 3比較容易看明白,因爲它們都經過了一次++ii++,但是爲什麼最後的結果是8呢,按照前三個例子得到的結論,k應該是7纔對(k = 1 + 2 + 2 + 2)

接下來這句可能會有點繞,重點在於第一個i++操作說明算出k的流程應該是(k = 1 + 3 + 2 + 2)第一個i++是完成的的應爲後邊執行的++i只有i = 2 + 1纔可以得到3。

例子5:

結果是a = 2可以說明兩次a++都有執行到,b = 1是將第一次a++的值賦給了它。

總結

待我找到能從底層說明上述現象的原因再補充。


  1. Postfix Increment and Decrement Operators: ++ and – ↩︎

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章