在注释掉未使用的行后,开关情况将不会编译

这里是我的代码:

#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语句中的每一种情况,在技术上来说,是一个标签。对于一些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;
}

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

http://stackoverflow.com/questions/30726663/switch-case-wont-compile-after-commenting-out-an-unused-line

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:在注释掉未使用的行后,开关情况将不会编译