3 回答

TA貢獻1770條經(jīng)驗 獲得超3個贊
這是一個很好的介紹。這是概述:
通用選擇是通過新關(guān)鍵字_Generic實現(xiàn)的。語法類似于類型的簡單switch語句:_Generic( 'a', char: 1, int: 2, long: 3, default: 0) 取值為2(字符常量在C中為int)。
基本上,它的工作方式類似于的switch,其中標簽是類型名稱,將根據(jù)第一個表達式的類型('a'上述)進行測試。結(jié)果成為評估的結(jié)果_Generic()。

TA貢獻1875條經(jīng)驗 獲得超3個贊
我看到的最好的例子啟發(fā)了以下(可運行的)示例,該示例為破解內(nèi)省開辟了各種奇特的可能性...
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#define typename(x) _Generic((x), /* Get the name of a type */ \
\
_Bool: "_Bool", unsigned char: "unsigned char", \
char: "char", signed char: "signed char", \
short int: "short int", unsigned short int: "unsigned short int", \
int: "int", unsigned int: "unsigned int", \
long int: "long int", unsigned long int: "unsigned long int", \
long long int: "long long int", unsigned long long int: "unsigned long long int", \
float: "float", double: "double", \
long double: "long double", char *: "pointer to char", \
void *: "pointer to void", int *: "pointer to int", \
default: "other")
#define fmt "%20s is '%s'\n"
int main() {
size_t s; ptrdiff_t p; intmax_t i; int ai[3] = {0}; return printf( fmt fmt fmt fmt fmt fmt fmt fmt,
"size_t", typename(s), "ptrdiff_t", typename(p),
"intmax_t", typename(i), "character constant", typename('0'),
"0x7FFFFFFF", typename(0x7FFFFFFF), "0xFFFFFFFF", typename(0xFFFFFFFF),
"0x7FFFFFFFU", typename(0x7FFFFFFFU), "array of int", typename(ai));
}
╔═══════════════╗
═════════════════╣ Amazeballs... ╠═════════════════════════════════════
╚═══════════════╝
size_t is 'unsigned long int'
ptrdiff_t is 'long int'
intmax_t is 'long int'
character constant is 'int'
0x7FFFFFFF is 'int'
0xFFFFFFFF is 'unsigned int'
0x7FFFFFFFU is 'unsigned int'
array of int is 'other'

TA貢獻1893條經(jīng)驗 獲得超10個贊
我使用的是clion 1.2.4,而clion現(xiàn)在不支持c11,因此我在c99中使用以下代碼而不是_Generic
#include <stdio.h>
int main(int argc, char **argv) {
char *s;
if (__builtin_types_compatible_p(__typeof__(s), long)) {
puts("long");
} else if (__builtin_types_compatible_p(__typeof__(s), char*)) {
puts("str");
}
return (0);
};
- 3 回答
- 0 關(guān)注
- 957 瀏覽
添加回答
舉報