본문 바로가기
Error Handling

C++ Invalid operands to binary expression

by songmoro 2022. 12. 23.
728x90

C++에서 using namespace std;를 통해 namespace를 지정했을 때

 

함수 명이 겹치는 함수를 사용했을 경우 Invalid operands to binary expression 에러가 발생할 수 있다.

이는 함수 명이 예를 들어 socket의 bind를 사용하고자 했지만 컴파일러는 std의 bind를 의미하는 줄 알고 사용하는 경우이다.

 

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

int main(void){
    int sockfd;
    struct sockaddr_in my_addr;
    
    if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket Error\n");
        exit(1);
    }
    
    if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0){
       //
    }
}

 

위의 코드에선 if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0) 부분에서 에러가 발생한다.

 

아래와 같이 if(::bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0) 처럼 ::bind()의 형태로 바꿔주면 된다.

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

int main(void){
    int sockfd;
    struct sockaddr_in my_addr;
    
    if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket Error\n");
        exit(1);
    }
    
    if(::bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0){
       //
    }
}
728x90