简体   繁体   English

无法理解C中程序的输出

[英]Unable to understand the output of program in C

EDIT: This question is not duplicate as the behavior is not undefined in this case. 编辑:此问题不是重复的,因为在这种情况下行为不是不确定的。

Why does the below program print the output as 231 in first line? 为什么下面的程序在第一行中将输出打印为231?

I have two doubts regarding this: 我对此有两个疑问:

  1. As I am doing postfix increment the value of x shouldn't have been increased before the I call max function. 当我做后缀增量时,在调用max函数之前不应增加x的值。 So the output should have been 1 in the first place instead of 2 according to me. 因此输出应该是第一位的,而不是我认为的2位。 What am I missing? 我想念什么?

     #define prn(a) printf("%d",a) #define print(a,b,c) prn(a), prn(b), prn(c) #define max(a,b) (a<b)? b:a main() { int x=1, y=1; print(max(x++,y),x,y); printf("\\n"); print(max(x++,y),x,y); } 

    Output: 输出:

     231 451 
  2. The postfix operation occurs after execution of the statement? 后缀操作是否在执行语句后发生? Consider the example below. 考虑下面的示例。

     int main() { int x = 0, y = 1; int a = x++ /*x is incremented hereafter?*/+ y; // line 1 /* Or x is incremented now after execution of above line?*/ // line 2 int b = 0; } 

let me take this line 让我走这条线

               print(max(x++,y),x,y);

One important point to note is that the C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before it is compiled. 需要注意的重要一点是C预处理程序是一个宏预处理程序(允许您定义宏),可以在编译程序之前对其进行转换。 These transformations can be inclusion of header file, macro expansions etc. 这些转换可以包括头文件,宏扩展等。

All preprocessing directives begins with a # symbol. 所有预处理指令均以#符号开头。 For example, 例如,

                #define PI 3.14

tells the compiler to replace the value PI with 3.14 where ever it sees. 告诉编译器在任何地方将PI值替换为3.14。

           c source code->preprocessor->compiler

therefore print(max(x++,y),x,y) is expanded in macro to 因此print(max(x ++,y),x,y)在宏中扩展为

           1.      prn((x++<y) ? y:x++), prn(x), prn(y) 

        2. printf("%d",(x++<y)? y:x++), printf("%d",x), printf("%d",y);.

here it gets processed you can check two things carefully here 在这里得到处理,您可以在这里仔细检查两件事

while checking 在检查时

               x++<y ,the x++ value is 1

then after that the x value becomes 2 然后x值变成2

so 2 is printed 所以打印2

and then while printing also we wrote x++ that means here x++ VALUE IS 2 but 然后在打印时我们也写了x ++,这意味着x ++ VALUE是2,但是

after that x value is 3 之后x值为3

so 3 is printed and it follows y as 1 所以3被打印出来,其后跟y为1

that 's how it works 就是这样

2.TO give you a great intuition on preincrement and post increment 2.TO给你一个很好的直觉和后期增量

let me take an example 让我举个例子

               int x=2;//value of x is 2

               x++;//here x++ value is 2

after this line execution x value changed to 3 在此行执行后,x值更改为3

               ++x//here x++ value is 4 and also x value is 4.

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

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