IT이야기

사용되지 않는 행을 주석 처리한 후 스위치케이스가 컴파일되지 않음

cyworld 2022. 5. 18. 21:59
반응형

사용되지 않는 행을 주석 처리한 후 스위치케이스가 컴파일되지 않음

내 암호는 다음과 같다.

#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.

제가 무엇을 빠뜨리고 있나요?

스위치 문장의 각 사례는 기술적으로 말하면 라벨이다.어떤 불명확하고 오래된 이유로, 당신은 라벨 뒤의 첫 번째 줄로 가변 선언을 할 수 없다.과제를 주석 처리하여

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

선로

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

라벨 뒤에 첫 줄이 되다AF_INET:내가 말했듯이 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;
}

어쨌든, 나는 이것이 더 좋은 코딩 연습이라고 생각한다.

승인된 답변에 대한 보완책으로 사례 레이블 앞에 변수를 선언할 수 있다.

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

아니면 그냥 빈 문장으로.

참조URL: https://stackoverflow.com/questions/30726663/switch-case-wont-compile-after-commenting-out-an-unused-line

반응형