LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 750|回复: 2

这个goto可以换掉吧?

[复制链接]
发表于 2005-7-11 22:17:24 | 显示全部楼层 |阅读模式
来自名著Unix Network Programming (UNP) v3
unpv13e/lib/readline.c


  1. static ssize_t
  2. my_read(int fd, char *ptr)
  3. {

  4.         if (read_cnt <= 0) {
  5. again:
  6.                 if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {
  7.                         if (errno == EINTR)
  8.                                 goto again;
  9.                         return(-1);
  10.                 } else if (read_cnt == 0)
  11.                         return(0);
  12.                 read_ptr = read_buf;
  13.         }

  14.         read_cnt--;
  15.         *ptr = *read_ptr++;
  16.         return(1);
  17. }
复制代码

基础教科书一再强调不用goto(标识符可见域污染危险、程序结构破坏等罪名),不各知道UNP为什么还用。改成下面这样,能不能达到等价呢?

  1. static ssize_t
  2. my_read(int fd, char *ptr)
  3. {

  4.         if (read_cnt <= 0) {
  5.                 while(1) {
  6.                         if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {
  7.                                 if (errno == EINTR)
  8.                                         continue;
  9.                                 return(-1);
  10.                         } else if (read_cnt == 0)
  11.                                 return(0);
  12.                         else
  13.                                 break;
  14.                 }
  15.                         read_ptr = read_buf;
  16.         }

  17.         read_cnt--;
  18.         *ptr = *read_ptr++;
  19.         return(1);
  20. }

复制代码
发表于 2005-7-11 22:49:37 | 显示全部楼层
goto不是绝对不可以用,适当的使用可以使代码更简洁,特别是从深层嵌套的循环中跳出来时。
回复 支持 反对

使用道具 举报

发表于 2005-7-12 11:00:02 | 显示全部楼层
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表