发现char* 有几个有趣但平时没注意的特性。
2:例
- #include <stdio.h>
-
-
static void
-
tst_str_1(void)
-
{
-
printf("hello" "world\n");
-
printf("hello"
-
"world\n");
-
// printf("hello", "world");
-
}
-
-
static void
-
tst_str_2(void)
-
{
-
char *as[] = {"hello",
-
"world"
-
"AAAAA",};
-
-
printf("%s ---- %s\n", as[0], as[1]);
-
}
-
-
static void
-
initStr(char *s)
-
{
-
static char sep = ' ';
-
printf("%c%s", sep, s);
-
sep = ',';
-
}
-
-
static void
-
tst_str_3(void)
-
{
-
int i;
-
for (i = 0; i < 3; i++)
-
initStr("Hello");
-
printf("\n");
-
}
-
-
int
-
main(int argc, char **argv)
-
{
-
tst_str_1();
-
tst_str_2();
-
tst_str_3();
-
-
return 0;
- }
3:结果
- xdzh@xdzh-laptop:/media/home/work/c$ gcc -Wall -o tst-str tst-str.c
-
xdzh@xdzh-laptop:/media/home/work/c$ ./tst-str
-
helloworld
-
helloworld
-
hello ---- worldAAAAA
- Hello,Hello,Hello
- 相邻字符串常量将被自动合成一个字符串
- 除最后一个字符串外,其余字符串末尾的'\0'将被自动删除
- 划线的部分一个少一个逗号一个多一个逗号,不过都不会引起错误,但是需要注意
- 第三个,利用static静态变量的特性,实现一个有趣的情况,可以减少分支和条件测试