在注释掉一个未使用的行之后,switch-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; } 

编译好。

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

 //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在技术上都是一个标签。 由于某些模糊和古老的原因 ,不允许将variables声明作为标签之后的第一行。 通过评论的任务

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

线

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

成为标签AF_INET:之后的第一行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; } 

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

作为接受的答案的补充,你可以在case标签之前声明你的variables。

 switch(a) { int b; //can't initialize variable here case 0: ... } 

或者只是使用一个空的陈述。