簡體   English   中英

無法理解C程序的輸出

[英]Not able to understand the output of C program

C中有這段代碼

int fun()
{
  static int num = 40;
  return num--;
}

int main()
{
  for(fun(); fun(); fun())
  {
    printf("%d ", fun());
  }
  getchar();
  return 0;
}

輸出結果為:38 35 32 29 26 23 20 17 14 11 8 5 2

我無法弄清楚為什么該程序不能繼續打印到2以上。即,在底片中。它不應該繼續打印... -1 -4 -7 ....無限循環有人可以解釋嗎?

fun()的計算結果為0

for(fun(); fun(); fun())
//         ^    

0等於C中的false ,因此循環退出。

該代碼依賴於num - 1是3的倍數的事實,因為fun()在循環開始時被評估一次,然后在每個循環中被評估3次。 例如,如果您將定義更改為

static int num = 41;

fun()將在錯誤的位置返回0 ,並且循環將繼續為負數。

整個魔術發生在for()循環內。

基本格式如下:

for (<pre-iteration>; <condition>; <post-iteration>)
    <code>

預迭代中的代碼將在第一次迭代/循環之前執行一次。 每次迭代之前都會評估代碼內部條件 如果結果值為true ,則循環繼續;如果結果為false ,則循環結束。 迭代后的代碼在每次迭代之后執行。

為了使整個代碼更易於理解,重要的是要知道您也可以使用while()循環編寫這樣的for()循環:

<pre-iteration>
while (<condition>) {
    <code>
    <post-iteration>
}

回到您的示例:

for (fun(); fun(); fun())
{
    printf("%d ", fun());
}

使用while()可以這樣寫:

fun();
while (fun()) {
    printf("%d ", fun());
    fun();
}

由於fun()將返回靜態值num的值,然后將其遞減1因此第一次迭代將如下所示:

// This is going to be the first call, so the static variable is initialized: num = 40
fun();                    // returns 40; num = 39
while (fun()) {           // returns 39; num = 38 (true -> loop continues)
    printf("%d ", fun()); // returns 38; num = 37 (-> 38 is written to console)
    fun();                // returns 37; num = 36
}

下一次迭代(出於明顯的原因,不再執行循環前的代碼):

fun();                    // no longer executed
while (fun()) {           // returns 36; num = 35 (true -> loop continues)
    printf("%d ", fun()); // returns 35; num = 34 (-> 35 is written to console)
    fun();                // returns 34; num = 33
}

這一直持續到最后一次迭代:

fun();                    // no longer executed
while (fun()) {           // returns 0; num = -1 (false -> loop exits)
    printf("%d ", fun()); // no longer executed
    fun();                // no longer executed
}

我無法弄清楚為什么該程序不能繼續打印到2以上。即,在底片中。它不應該繼續打印... -1 -4 -7 ....無限循環有人可以解釋嗎?

是的,它可能會繼續,但前提是對fun()特定調用不會返回0 ,即將num的初始值設置為41且程序將無限期運行(或至少直到返回值恰好在0變為0時)一點)。

讓我們看看在for循環中第二次調用fun()會發生什么。 首次進入循環時,已經對fun()進行了一次評估,因此num39 第二次進入循環, fun()已經執行了三遍,現在是36 此過程一直持續到最終對fun()的第二次調用返回0為止。 在C中, 0表示false ,因此循環在該階段終止。

for(fun(); fun(); fun())

for()循環的第二部分是一個條件-如果fun()返回0(解釋為false),則循環終止。 最近,我放屁了,寫了一個聲明,說條件只對正數才成立。

什么時候

printf("%d ", fun());

運行時,fun()的值為2然后執行下一條命令中的最后一個fun()以增加計數器(通常):

for(fun(); fun(); fun())

fun()為1。

然后執行繼續for循環的條件,這是第二個fun():

for(fun(); fun(); fun())

此時,fun()為0,這使for循環停止。

當您打印fun() ,您看不到num的實際值,而是num+1的值。

這是因為您使用的是后綴減量( num-- ),而不是前綴減量( --num )。

因此,當您打印2時, num的實際值為1。

在此迭代結束時,將調用fun() ,將num設置為0。

在下一次迭代的開始, num被評估為false,並且for循環終止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM