cgg之字面值

时间:2023-03-08 22:44:17

字面值时源代码中用来描述固定值的记号,可能是整数、浮点数、字符或者字符串

2.1 整数常量

除了常见的十进制数外,还有八进制(以数字0开头)或者十六进制(0x/0X)表示法。

#include <stdio.h>

int main()
{
int x = ;
int y = 0x0A; printf("x=%d,y=%d\n",x,y);
return ;
}

输出:

x=8,y=10

常量类型可以通过后缀来区分类型

0x200 -->int
200U -->unsigned int 0L -->long
0xf0f0UL -->unsigned long 0777LL --->long long
0xFFULL --->unsigned long long

2.2 浮点常量

默认浮点常量是double,可以用F后缀表示float,用L后缀表示long double

    printf("%f\n",0.111111111F);
printf("%f\n",0.11111);
printf("%Lf\n",.9999999999L);
printf("%Lf\n",.99L);

输出:

0.111111
0.111110
1.000000
0.990000

对于long double输出必须使用%Lf的格式,否则输出结果是错误的。

2.3 字符常量

字符常量默认是int类型,除非用前置L表示wchar_t宽字符类型

#include <stdio.h>
#include <locale.h> int main()
{
int i; printf("%c,%c,%c\n",c,c2,c3); setlocale(LC_CTYPE,"en_US.UTF-8");
wchar_t wc = L'中'; char buf[] = {}; int len = wctomb(buf,wc); printf("%d\n",len); for(i = ; i<len; i++)
printf("0x%02X ",(unsigned char)buf[i]);
printf("\n"); return ;
}

输出:

0xE4 0xB8 0xAD 

使用python进行验证

>>> astr='中'
>>> astr
'\xe4\xb8\xad'

结果正确。

2.4 字符串常量

C语言中的字符串是一个以NULL(也就是\0)结尾的char数组。

空字符串在内存中占用一个字节,包含一个NULL字符。

char s[] = "Hello,World!\n";
printf("strlen=%d\n",strlen(s));
printf("sizeof=%d\n",sizeof(s)); #输出结果为: strlen=
sizeof=
------------------------------------------------------------------
char* ps = "Hello,World!\n";
printf("strlen=%d\n",strlen(ps));
printf("sizeof=%d\n",sizeof(ps)); #输出结果为:
strlen=
sizeof=8 #是指针char*代表的大小

同样可以使用L前缀声明一个宽字符串。

#include <stdio.h>
#include <locale.h> int main()
{
int i; printf("%c,%c,%c\n",c,c2,c3); setlocale(LC_CTYPE,"en_US.UTF-8");
wchar_t* ws = L"中国人"; char buf[] = {}; size_t len = wcstombs(buf,ws,); printf("%ls\n",ws);
printf("%d\n",len); for(i = ; i<len; i++)
printf("0x%02X ",(unsigned char)buf[i]);
printf("\n"); return ;
}

输出:

中国人

0xE4 0xB8 0xAD 0xE5 0x9B 0xBD 0xE4 0xBA 0xBA 

使用python进行验证:

>>> astr="中国人"
>>> astr
'\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba'

和char字符串类似,wchar_t字符串以一个4字节的NULL结束。

#include <stdio.h>
#include <locale.h> int main()
{
int i; setlocale(LC_CTYPE,"en_US.UTF-8");
wchar_t ws[] = L"中国人"; printf("%ls\n",ws); printf("len=%d,size=%d\n",wcslen(ws),sizeof(ws)); int len = sizeof(ws);
unsigned char* b = (unsigned char*)ws; for(i = ; i<len; i++)
printf("0x%02X ",b[i]);
printf("\n"); return ;
}

输出结果为:

中国人
len=3,size=16
0x2D 0x4E 0x00 0x00 0xFD 0x56 0x00 0x00 0xBA 0x4E 0x00 0x00 0x00 0x00 0x00 0x00

编译器会自动连接相邻的字符串,便于在宏或者代码中更好地处理字符串。

对于源代码中超长的字符串,除了使用相邻字符串外,还可以用"\"在行尾换行,这个在很多语言都支持。

#include <stdio.h>
#define WORLD "world!"
int main()
{
char* s = "Hello" " "WORLD"\n"; char* s2 = "Hello"
" World!\n"; char* s3 = "Hello \
World!\n";
printf("%s",s);
printf("%s",s2);
printf("%s",s3);
return ;
}

输出结果为:

Hello world!
Hello World!
Hello World!