[英]Parenthesis and assignment operator order
我正在編寫c表達式解析器並發現我不理解的行為:
#include <iostream>
#include <sstream>
int main()
{
std::string string1;
std::string string2 = std::string((string1 = std::string("first")) + " " + (string1 = std::string("second")));
std::cout << string1 << std::endl;
std::cout << string2 << std::endl;
int int1;
int int2 = (int1 = 1) + (int1 = 2);
std::cout << int1 << std::endl;
std::cout << int2 << std::endl;
std::cin.get();
return 0;
}
輸出:
first
first first
2
4
我曾預料到:
second
first second
2
3
在C#中運行相同的程序時,我得到了預期的輸出。 你能解釋一下那里發生了什么嗎?
C#代碼: https : //gist.github.com/Kukkimonsuta/59543cfc4f7f73b8bebd
此代碼在C ++中具有未定義的行為,因為單個表達式對同一變量產生多個副作用(即,對string1
兩個賦值)。 int1
變量也是如此。
在您的情況下,編譯器將按照與您預期相反的順序應用這兩個副作用。 即使它按照您預期的順序應用它們,該程序仍然無效。
在C#中運行相同的程序時,我得到了預期的輸出。
與C ++不同,C#並沒有給編譯器開發人員留下太多的決定。 這些表達式的評估順序以及在C ++中產生未定義行為的許多其他表達式都由語言標准很好地定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.