c - 注释掉未使用的行后,Switch-case 不会编译

标签 c

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main (void) {

  struct addrinfo hints; 
  memset (&hints, 0, sizeof hints);

  hints.ai_family = AF_UNSPEC; 
  hints.ai_socktype = SOCK_DGRAM;  
  hints.ai_flags = AI_CANONNAME;   

  struct addrinfo *res;

  getaddrinfo ("example.com", "http", &hints, &res);
  printf ("Host: %s\n", "example.com");

  void *ptr;

  while (res != NULL) {
    printf("AI Family for current addrinfo: %i\n", res->ai_family);
    switch (res->ai_family) {
      case AF_INET:
        ptr = (struct sockaddr_in *) res->ai_addr;
        struct sockaddr_in *sockAddrIn = (struct sockaddr_in *) res->ai_addr;
        break;
    }
    res = res->ai_next;
  }
  return 0;
}

编译正常。

但是当我注释掉这一行时:

//ptr = (struct sockaddr_in *) res->ai_addr;

我会得到:

$ gcc ex4.c
ex4.c:30:9: error: expected expression
        struct sockaddr_in *sockAddrIn = (struct sockaddr_in *) res->ai_addr;
        ^
1 error generated.

我错过了什么?

最佳答案

从技术上讲,switch 语句中的每个 case 都是一个标签。对于一些obscure and old reasons , 不允许将变量声明作为标签后的第一行。通过注释掉作业

ptr = (struct sockaddr_in *) res->ai_addr;

线

struct sockaddr_in *sockAddrIn = (struct sockaddr_in *) res->ai_addr;

成为标签 AF_INET: 之后的第一行,正如我所说,这在 C 中是非法的。

解决方案是将所有 case 语句包装在大括号中,如下所示:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main (void) {

  struct addrinfo hints; 
  memset (&hints, 0, sizeof hints);

  hints.ai_family = AF_UNSPEC; 
  hints.ai_socktype = SOCK_DGRAM;  
  hints.ai_flags = AI_CANONNAME;   

  struct addrinfo *res;

  getaddrinfo ("example.com", "http", &hints, &res);
  printf ("Host: %s\n", "example.com");

  void *ptr;

  while (res != NULL) {
    printf("AI Family for current addrinfo: %i\n", res->ai_family);
    switch (res->ai_family) {
      case AF_INET:
      {
        ptr = (struct sockaddr_in *) res->ai_addr;
        struct sockaddr_in *sockAddrIn = (struct sockaddr_in *) res->ai_addr;
        break;
      }
    }
    res = res->ai_next;
  }
  return 0;
}

无论如何,我认为这是更好的编码实践。

关于c - 注释掉未使用的行后,Switch-case 不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30726663/

相关文章:

c - 将 pthread_t 传递给函数时出现奇怪的错误

c - 浮点加法 2.5 + 2.5 = 4.0? RPN

c - 如何打印内存和缓冲区的长度?

c - 这个 C 表达式是如何求值的

java - 使用 JNI 将字符串从 C 发送到 Java

c - 标准 linux 链接到首选文件管理器?

c - 在 C if 语句中检查 NULL 时最好使用 OR 或 AND?

c - 我的 C 程序运行已停止

c - 返回指针后出现段错误

c - 在 C 中缩小 BMP 图像