C語言筆記-用結構體讓函式可以返回多個資料
C與言的函式無法回傳一個以上的值,不過可以透過回傳一個結構來完成: 範例: #include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double width,height; }size_s; size_s width_height ( char * papertype){ return ! strcasecmp(papertype, "A4" ) ? (size_s){.width = 210 ,.height = 297 } : ! strcasecmp(papertype, "Letter" ) ? (size_s){.width = 216 ,.height = 279 } : ! strcasecmp(papertype, "Legal" ) ? (size_s){.width = 2216 ,.height = 356 } : (size_s){.width = NAN,.height = NAN}; } int main ( void ) { size_s a4size = width_height( "A4" ); printf( "width=%g,height=%g \n " ,a4size.width,a4size.height); } 透過 condition?iftrue:else的格式來取代switch,而且也可以放在return後面 "21centry c"一書的作者很提倡這種風格。 除了用結構體之外,也可以用指標透過參數在函式內修改來完成: void width_height ( char * papertype, double * width, double * height); 這種風格是我常用的方法,也是最常見的格式,不過很容易混淆輸入跟輸出。