Search code examples
c++cassignboolean-operations

Does it make sense to analyse the boolean result of an variable assignment?


I was reading a code just now and I found a very strange code line written by another programmer:

if ((socket_obj->client_fd = accept(socket_obj->server_fd, (struct sockaddr *)&socket_obj->client_address, &fromlen)) < 0)

If I understood correctly, the line is calling the socket.h function accept which returns an integer value. Once the function is finished, this value is assigned to socket_obj->client_fd and then, the assignment operation is evaluated if it is lower then 0.

But wouldn't it be always higher then 0 since the boolean result of an value assignment is always true? I mean, won't the following line always return true?

if (myVariable = 0)

I first thought this was a coding mistaken and changed the code so the assignment first occurs and later the value inside socket_obj->client_fd is evaluated against 0, but then I found another place in the code where the same situation occurs, so I can't assume it's an isolated mistake.

I'ld like to know, then, if my interpretation is correct.


Solution

  • An assignment does not return true. Try it out for yourself. An assignment returns the value that has been assigned.

    int main() {
        int a;
        std::cout << ( (a = 0) ? "true" : "false" ) << '\n';
        return 0;
    }
    

    Note that the resulting value does not need to be true or false. For example, that's why you can do:

    int x, y;
    x = y = 4; // both x and y are 4 now
    

    This is equivalent to:

    x = ( y = 4 );
    

    And since y's assignment returns the value assigned to y, which is 4, x also gets it.