Chinaunix首页 | 论坛 | 博客
  • 博客访问: 359253
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-07-13 23:11:24

1:概述
     发现char* 有几个有趣但平时没注意的特性。

2:例
  1. #include <stdio.h>

  2. static void
  3. tst_str_1(void)
  4. {
  5.     printf("hello" "world\n");
  6.     printf("hello"
  7.         "world\n");
  8. //    printf("hello", "world");
  9. }

  10. static void
  11. tst_str_2(void)
  12. {
  13.     char *as[] = {"hello",
  14.         "world"
  15.         "AAAAA",};

  16.     printf("%s ---- %s\n", as[0], as[1]);
  17. }

  18. static void
  19. initStr(char *s)
  20. {
  21.     static char sep = ' ';    
  22.     printf("%c%s", sep, s);
  23.     sep = ',';
  24. }

  25. static void
  26. tst_str_3(void)
  27. {
  28.     int i;
  29.     for (i = 0; i < 3; i++)    
  30.         initStr("Hello");
  31.     printf("\n");
  32. }

  33. int
  34. main(int argc, char **argv)
  35. {
  36.     tst_str_1();    
  37.     tst_str_2();    
  38.     tst_str_3();    

  39.     return 0;
  40. }

3:结果
  1. xdzh@xdzh-laptop:/media/home/work/c$ gcc -Wall -o tst-str tst-str.c
  2. xdzh@xdzh-laptop:/media/home/work/c$ ./tst-str
  3. helloworld
  4. helloworld
  5. hello ---- worldAAAAA
  6.  Hello,Hello,Hello
  • 相邻字符串常量将被自动合成一个字符串
  • 除最后一个字符串外,其余字符串末尾的'\0'将被自动删除
  • 划线的部分一个少一个逗号一个多一个逗号,不过都不会引起错误,但是需要注意
  • 第三个,利用static静态变量的特性,实现一个有趣的情况,可以减少分支和条件测试



阅读(1292) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~