[問題] 這段三元運算子的意思是?

看板C_and_CPP (C/C++)作者 (沒有存在感的人)時間10年前 (2015/11/28 01:02), 10年前編輯推噓2(2013)
留言15則, 6人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux + gcc5.2.1 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 看到一個面試題目: typedef int* TYPE; int f(TYPE x) ; //Allocate an array of two integers; //return 0 if the allocation succeeded, 1 otherwise. //Return the allocated array in x int f(TYPE x) { int* ret = (int*) malloc(sizeof(int[2])); return ret ? *x=ret, 0:1 ; //-> 這行不懂 } TYPE 該怎麼定義? 我試過只有typedef int* TYPE 可以編譯過 可是我不懂最後一行 一般來說三元運算子不是 val = x ? y : z ; 等於 if(x == true) val = y; else val = z; 可是函式這行我不懂... 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 以下是我的測試程式: #include <stdio.h> #include <stdlib.h> typedef int* TYPE; int f(TYPE x) { int* ret = (int*) malloc(sizeof(int[2])); return ret ? *x=ret, 0:1 ; } int main(void) { TYPE a; printf("%d\n", f(a)); return 0; } 補充說明(Supplement): 編譯結果(gcc Q_15.c -Wall): Q_15.c: In function ‘f’: Q_15.c:7:20: warning: assignment makes integer from pointer without a cast [-Wint-conversion] return ret ? *x=ret, 0:1 ; ^ Q_15.c: In function ‘main’: Q_15.c:12:5: warning: ‘a’ is used uninitialized in this function [-Wuninitialized] printf("%d\n", f(a)); ^ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.41.112.247 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1448643722.A.577.html ※ 編輯: wtchen (90.41.112.247), 11/28/2015 01:11:09

11/28 01:36, , 1F
operator, 會把整串敘述作完 然後回傳最右邊的那個值
11/28 01:36, 1F

11/28 01:38, , 2F
他只是在return 0之前多塞了*x=ret進去而已
11/28 01:38, 2F

11/28 02:48, , 3F
所以這邊一樣先判斷ret是true or false,然後不管判斷
11/28 02:48, 3F

11/28 02:49, , 4F
結果如何都執行*x=ret?
11/28 02:49, 4F

11/28 02:50, , 5F
然後ret==true時 ret=0,反之則ret=1?
11/28 02:50, 5F

11/28 06:03, , 6F
? : 中間的東西會自動成為一組, 所以只有在 ret 為真時
11/28 06:03, 6F

11/28 06:03, , 7F
才會發生 assignment, 其他就和你理解的一樣
11/28 06:03, 7F

11/28 06:04, , 8F
if (ret) { *x = ret; return 0; } else { return 1; }
11/28 06:04, 8F

11/28 18:21, , 9F
了解,感謝!
11/28 18:21, 9F

11/29 21:57, , 10F
其實你把*x=ret前後加個()應該就懂了
11/29 21:57, 10F

11/29 21:57, , 11F
跟某些for迴圈的trick一樣的做法
11/29 21:57, 11F

11/30 22:27, , 12F
話說這個f應該要改成 int f(TYPE *x) 才對?
11/30 22:27, 12F

11/30 22:30, , 13F
http://ideone.com/nlC5fC 整個程式改成這樣
11/30 22:30, 13F

12/03 00:29, , 14F
不懂為何要改int f(TYPE *x) (該程式是照抄面試題)
12/03 00:29, 14F

12/03 01:14, , 15F
它是藉 x "回傳"一個 TYPE 型態變數, 當然要 TYPE*...
12/03 01:14, 15F
文章代碼(AID): #1MM8oALt (C_and_CPP)
文章代碼(AID): #1MM8oALt (C_and_CPP)