1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#include
#defineGENERAL_ABS(x)_Generic((x),int:abs,float:fabsf,double:fabs)(x)
intmain(
void
)
{
printf
(
"intabs:%d\n"
,GENERAL_ABS(-12));
printf
(
"floatabs:%f\n"
,GENERAL_ABS(-12.04f));
printf
(
"doubleabs:%f\n"
,GENERAL_ABS(-13.09876));
inta=10;
intb=0,c=0;
_Generic(a+0.1f,
int
:b,
float
:c,
default
:b)++;
printf
(
"b=%d,c=%d\n"
,b,c);
_Generic(a+=1.1f,
int
:b,
float
:c,
default
:b)++;
printf
(
"a=%d,b=%d,c=%d\n"
,a,b,c);
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#include
#include
size_tUTF16StrLen(constchar16_t*utf16String)
{
if
(utf16String==NULL)
return0;
size_tindex;
for
(index=0;utf16String[index]!=u
'\0'
;index++);
returnindex;
}
size_tUTF16ToUTF8(
char
*mbBuffer,constchar16_t*utf16String)
{
if
(mbBuffer==NULL||utf16String==NULL)
return0;
mbstate_tstate={};
size_tmbIndex=0;
for
(intutf16Index=0;utf16String[utf16Index]!=u
'\0'
;utf16Index++)
{
constsize_tlength=c16rtomb(&mbBuffer[mbIndex],utf16String[utf16Index],&state);
mbIndex+=length;
}
mbBuffer[mbIndex]=
'\0'
;
returnmbIndex;
}
intmain(intargc,
char
*argv[])
{
char16_tch=u
'好'
;
charchBuffer[64];
mbstate_tstate={};
size_tlength=c16rtomb(chBuffer,ch,&state);
chBuffer[length]=
'\0'
;
printf
(
"TheUTF-8characterlengthis:%zu,andthecharacteris:%s\n"
,length,chBuffer);
constchar*utf8Str=u8
"你好,世界。"
;
printf
(
"TheUTF-8stringis:%s\n"
,utf8Str);
constchar16_t*utf16Str=u
"你好,世界。"
;
printf
(
"Theutf16stringlengthis:%zu\n"
,UTF16StrLen(utf16Str));
length=UTF16ToUTF8(chBuffer,utf16Str);
printf
(
"TheUTF-8stringlengthis:%zu,andthecontentis:%s\n"
,length,chBuffer);
printf
(
"IftheconvertedUTF-8stringisequaltotheoriginalone?%s\n"
,
strcmp
(chBuffer,utf8Str)==0?
"YES"
:
"NO"
);
}
|