简体   繁体   English

当程序与 a+++b 一起打印时,根据词法分析,错误 output for a++ +b

[英]Getting wrong output for a++ +b according to lexical analysis when the program is printed along with a+++b

I wrote the following C program to find the output for a+++b我写了下面的C程序来找到a+++b的output

#include<stdio.h>
int main()
{
    int a=5, b=2; 
    printf("%d",a+++b);
}

And I'm getting the output as 7 which is correct according to lexical analysis.根据词法分析,我得到的 output 为 7,这是正确的。

Apart from that I wrote a separate program to find the output for a++ +b除此之外,我编写了一个单独的程序来为 a++ +b 找到 output

#include<stdio.h>
int main()
{
    int a=5, b=2; 
    printf("%d",a++ + b); 
}

For the above program again I'm getting output as 7 (which is again correct according to lexical analysis)对于上述程序,我再次将 output 设为 7(根据词法分析,这再次正确)

But when I wrote a program to print the outputs for both a+++b and a++ +b I'm getting different outputs但是当我编写一个程序来打印 a+++b 和 a++ +b 的输出时,我得到了不同的输出

#include<stdio.h>
int main()
{
    int a=5, b=2; 
    printf("%d",a+++b); 
    printf("\n%d",a++ + b); 
}

The output is 7 for a+++b (which is correct) and 8 for a++ +b (which is wrong). output a+++b 为 7(正确),a++ +b 为 8(错误)。

Can anyone point out the error in the third program?谁能指出第三个程序中的错误?

The issue here isn't the space in the second statement, it's the fact you have two of them.这里的问题不是第二个语句中的空格,而是你有两个的事实。 After the first statement (to be exact, after a++ is called), the value of a is incremented and is now 6. So a++ + b will clearly return 8 .在第一个语句之后(准确地说,在调用a++之后), a的值增加,现在是 6。所以a++ + b显然会返回8 If you omit the first printf call and just call the second one, you'll get 7 as you expect.如果您省略第一个printf调用而只调用第二个,您将得到7如您所愿。

a++ is post-fix increment. a++是后修复增量。 It evaluates to a and increments the variable a by 1 before the enclosing printf() is called in this case(*).在这种情况下(*)调用封闭的printf()之前,它计算为a并将变量a增加 1。

So after the first printf() the value of a is 6.所以在第一个printf()之后, a值为 6。

So what do you now expect from the second printf ?那么您现在对第二个printf有什么期望?

Operators like post-fix ++ are expressions (have a value) and instructions (have an effect).像 post-fix ++这样的运算符是表达式(有一个值)和指令(有一个效果)。 They cause endless confusion bugs and undefined behaviour to novices and bite the most seasoned programmers on the ass from time to time.它们会给新手带来无穷无尽的混乱错误和未定义的行为,并时不时地咬最老练的程序员。

(*) These operators are useful and have their place but exactly when these operators take effect is complex sometimes counter intuitive and I recommend you don't use them in complex expressions to begin with or even ever. (*) 这些运算符很有用并且有它们的位置,但是这些运算符何时生效有时很复杂,有时会违反直觉,我建议您不要在复杂的表达式中开始使用它们,甚至永远不要使用它们。 They're a bit of a throw back to when compilers didn't optimise code for you and the programmer had to help!当编译器没有为您优化代码并且程序员必须提供帮助时,它们有点回归!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM