C C 中switch用法的一種替換方式

2021-08-27 16:50:31 字數 846 閱讀 6705

在c/c++中,switch語句是經常被用到的,當switch內的case語句較多時程式有時顯得比較繁亂,此種情況下可以用另外一種實現方式替代switch。詳細用法見例子:

#include "stdafx.h"

float addfunc(float a, float b)

float subfunc(float a, float b)

float multiplyfunc(float a, float b)

float divisionfunc(float a, float b)

void fun1(float a, float b, int flag, float &result)

}//若函式無引數,且返回值為空,則應該這樣定義:

//typedef void (*basicoperationsfunc)();

typedef float (*basicoperationsfunc)(float a, float b);

basicoperationsfunc g_basicoperationsfunc = ;

void fun2(float a, float b, int flag, float &result)

int _tmain(int argc, _tchar* argv)

首先宣告乙個basicoperationsfunc,然後定義乙個basicoperationsfunc型別的陣列,這樣在fun2函式中就可以不用switch,而直接通過basicoperationfunc來呼叫相應的函式即可。如果在case條件比較多的情況下,這是一種不錯的替代方法。

還有其它推薦的方法嗎?

C C 中switch用法的一種替換方式

在c c 中,switch語句是經常被用到的,當switch內的case語句較多時程式有時顯得比較繁亂,此種情況下可以用另外一種實現方式替代switch。詳細用法見例子 include stdafx.h float addfunc float a,float b float subfunc floa...

Lua 實現switch的一種方案

local et case one 1 local et case two 2 local function do case one print do case one endlocal function do case two print do case two endlocal function...

alarm的一種用法。

alarm函式可以用於防止讀阻塞。但如果系統呼叫是自動重啟動的,當從sigalrm訊號處理程式返回時,read並不被中斷。在這種情形下,設定時間限制不起作用。一 源 cat n 10 10.c 1 include apue.h 23 static void sig alarm int sig no ...