Vin*_*uda 5 c c++ compiler-construction compilation
好吧,我想知道编译器“读取”代码的顺序是什么。例如:
假设我有以下代码片段:
int N, M;
N = M = 0;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,编译器会为 N 和 M 分离一部分内存(int,4 个字节),然后在第二行(我的疑问来自哪里),分为两件事,一:
编译器“读取”N 等于M 并且都等于0。
或者
编译器“读取”零,将其放入 M 的内存中,然后获取 M 的值,即零,并将其放入 N 的内存中。
换句话说,是从右到左,还是从左到右?
我不知道我的疑问是否清楚,但在我所做的测试中:
int i=0; /*I declared the variable i, and assign zero value to it*/
printf("%d", i++); /*Prints 0*/
printf("%d", i); /*Prints 1*/
Run Code Online (Sandbox Code Playgroud)
我理解上面的代码,在第二行,编译器似乎(根据我的理解)从左到右“读取”,将 i 值分配给类型 %d ,并且在打印之后,变量 i 递增,因为在第三行打印为1。
下面的代码片段反转了 ++ 的位置:
int i=0; /*I declared i variable to zero*/
printf("%d", ++i); /*Prints 1*/
printf("%d", i); /*Prints 1*/
Run Code Online (Sandbox Code Playgroud)
在这种情况下,在第二行,(根据我的理解)编译器从左到右“读取”,当编译器读取将打印的内容时(留在逗号之后,这个空间的名称是什么?) ,首先“读取”++ 并递增下面的变量(在本例中为 i),然后分配给要打印的 %d。
按顺序,编译器“读取”的顺序是什么?我有一些老师告诉我编译器从右到左从分号(;)开始“读取”,但编译器实际上有一个顺序?如果我上面说的有错,请纠正我。(我英语说得不太好)
谢谢!
I understand the above code, at the second line, the compiler seems(from what i undestood)"read" from left to right, assigning to the type %d the i value, and after print, the variable i is incremented, because at the third line it is printed as 1.
Run Code Online (Sandbox Code Playgroud)
这不是事情发生的顺序。
当调用 i++ 时,i 会增加 1。然后返回增加之前的值。
所以你的: printf("%d", i++)
实际上正在做:
int i = somevalue;
int temp = i;
i = i + 1;
printf("%d", temp);
Run Code Online (Sandbox Code Playgroud)
打印后 I 不增加。实际上是在印刷之前。
当你这样做时: printf("%d", ++i)
它确实:
int i = somevalue;
i = i + 1;
printf("%d", i);
Run Code Online (Sandbox Code Playgroud)
区别在于 temp 变量。在这种情况下,你的老师是正确的,它是从分号开始从右到左,因为:
它必须首先处理 I 的值。然后就可以打印了。实际上,如果您将每个操作或指令全部分解为单独的行,那么它实际上是从上到下的,如上所示。
| 归档时间: |
|
| 查看次数: |
2749 次 |
| 最近记录: |