2013-02-22 159 views
2

我有一個很小的代碼,但我無法得到爲什麼輸出是這樣的。
c函數參數評估和傳遞

#include <stdio.h> 

int f(int i, int j, int k); 

int main(int argc, char const *argv[]) 
{ 
    int a; 
    printf("enter a\n"); 
    scanf("%d",&a); 
    f(a,a++,a++); 
    printf("%d \n",a); 
    return 0; 
} 

int f(int i, int j, int k) 
{ 
    printf("function arguments \n"); 
    printf("%d %d %d\n",i,j,k); 
} 

輸入:4
輸出:6 5 4

+0

現在縮進請 – ogzd 2013-02-22 15:21:15

+1

可能重複[參數評估順序在C調用函數之前](http://stackoverflow.com/questions/376278/parameter-evaluation-order-before-a-function-calling-in -c) – unwind 2013-02-22 15:21:58

+0

用'gcc -Wall myprog.c -o myprog'和* gcc *編譯你的代碼會好心告訴你*警告:'a'上的操作可能是未定義的* – 2013-02-22 15:30:17

回答

4

中所標示的重複接受的答案不正確。


f(a,a++,a++); 

原因未定義行爲。它試圖修改參數a而沒有中間的順序點。此外,重要的是要注意函數參數的評估順序是未指定。它可以是:

  • 從左向右或
  • 右至左或
  • 任何神奇的順序編譯器選擇。

如果你正在使用gcc,你可以使用警示標誌-wsequence-point向您發出警告序列點相關的不確定的行爲。


在GCC如果你在嚴格的警告級別編譯程序,編譯器會給你這個診斷:

prog.c:10:18: error: operation on ‘a’ may be undefined [-Werror=sequence-point]
prog.c:10:18: error: operation on ‘a’ may be undefined [-Werror=sequence-point]


參考:

C99標準§6.5 .2.2:
第10段:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

注意,報價僅說有實際的函數調用前序列來看,它並不意味着存在的子表達式參數評價之間的序列點。

+0

@pce:它是**未定義的行爲**和**不是未指定的行爲**。證明在您引用的引用* C99§6.5.2。2p10 *表示在函數調用之前有一個序列點,它沒有說在評估子表達式參數之間有一個序列點。 – 2013-02-22 15:35:54

+0

@pce您如何看待C11§6.5p2? – Sebivor 2013-02-22 15:45:22

+0

@modifiablelvalue hehe,C11太棒了。^ – pce 2013-02-22 16:11:20

1

f(a,a++,a++);似乎是未定義的行爲,因爲:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.

當您使用未定義的行爲,沒有從C標準要求。

+0

Thanx to all。我還看到很多消息來源,我們無法說出指定的序列,但有一個神話,參數評估是從左到右,而傳球是從右到左。是這樣嗎? – 2013-03-03 10:34:53