在if中使用pre减量条件调用函数

时间:2010-06-07 12:12:08

标签: c

void display(int a)
{
  printf("\n%d",a);
  if(--a)
    display(a);
  printf("\n%d",a);
}

main()
{
  display(4);
}

请解释上述计划。我无法理解。什么是output.ya先生我得到了这样的4 3 2 1 0 1 2 3怎么样先生

8 个答案:

答案 0 :(得分:1)

循环如下:

Display(4): print "4", call display(3).
    Display(3): print "3", call display(2).
        Display(2): print "2", call display(1).
            Display(1): print "1", dont call display(0), print "0", returns to Display(2).
        Display(2): print "1", returns to Display(3).
    Display(3): print "2", returns to Display(4).
Display(4): print "3", exits.

结果将是:4 3 2 1 0 1 2 3

答案 1 :(得分:0)

函数display被递归调用,直到它的传入参数等于1.函数调用将在最后一次递归调用的末尾打印出1然后再打印0。

该函数意味着具有传递正值> = 1的前提条件。

--a表示将值减1,然后返回结果。所以它只会在!= 1时递归调用。

答案 2 :(得分:0)

您没有详细说明您不理解的内容。希望这会有所帮助:

// Declare Display function
void display(int a) 
{ 
// Print the value of a (passed in)
    printf("\n%d",a); 

// Reduce a by 1.  If the result is non-zero then recursively call the function with the value of a
    if(--a) 
        display(a); 

//Print the value of a again        
    printf("\n%d",a); 
} 

main() 
{ 
// Start with 4
    display(4); 
}

答案 3 :(得分:0)

在伪代码中:

display(a):
  print a
  decrement a
  if a > 0, call display (a)
  print a

main
  display (4)

答案 4 :(得分:0)

该功能从a和down打印所有数字,直到达到零,然后按递增顺序打印所有数字,直到达到-1。 输出将是:

4
3
2
1
0
1
2
3

答案 5 :(得分:0)

理解这样的示例的最简单方法可能就是编译它然后在调试器中单步执行它。观察堆栈并观察变化的价值。

答案 6 :(得分:0)

重要的是要意识到如何评估条件:

if (--a)表示:将a减一,然后检查其值

if (a--)表示检查a的值,然后将其减少一个

因此,在第一种情况下,关于是否在块中运行代码的决定是在变量减少之后完成的。另一方面,第二种情况首先评估变量,然后THEN减少它(然后在if语句中运行代码或不运行,具体取决于评估结果)

答案 7 :(得分:0)

  • 显示(4):打印“4”,呼叫显示(3),打印“3”。
  • 显示(3):打印“3”,呼叫显示(2),打印“2”。
  • 显示(2):打印“2”,呼叫显示(1),打印“1”。
  • 显示(1):打印“1”, 调用显示(0),打印“0”。
  • 所以结果将是:4 3 2 1 0 1 2 3