是否可以創建一個宏函數,其返回值是預定義的c變量數據類型之一?例如:C宏返回類型的變量
#include <stdio.h>
#define IND_I_ 0
#define IND_F_ 1
#define INT_FORMAT_ "%i"
#define FLOAT_FORMAT_ "%f"
// (Of course the following macros do not make the desired jobs)
// FORMAT_ macro would be used for the variable format:
#define FORMAT_(ind_)((ind_) == IND_I_ ? FOR_INT_ : FOR_FLOAT_)
// VAR_TYPE_ macro would be used for
// defining variable types and for the casting of variables:
#define VAR_TYPE_(ind_) ((ind_) == IND_I_ ? int : float)
int main(void)
{
VAR_TYPE_(IND_I_) first_var = 123; //here I want: int first_var = 123;
VAR_TYPE_(IND_F_) second_var = 345.789;
//Instead of:
//printf("int variable = " "%i" "\n", first_var);
//I would use:
printf("int variable = " FORMAT_(IND_I_) "\n", first_var);
printf("float variable = " FORMAT_(IND_F_) "\n", second_var);
printf("truncated real variable = " INT_FORMAT_ "\n", (VAR_TYPE_(IND_I_))second_var);
return 0;
}
@zwol,你認爲通過使用#if,#else,#elif指令可以解決我的問題嗎? – jruiz
@Olaf這是一個示範,確切地說明了「這可以完成」和「這不能完成」之間的界限。它不打算用於生產代碼。 – zwol
C11的那個邪惡'_Generic'結構可以做到。雖然格式字符串連接不起作用,但至少不是以任何直接的方式。 – doynax