Macro to avoid duplicate value

I am using a switch statement in C to evaluate the errno variable. According to the man page for send()

:

EAGAIN or EWOULDBLOCK

The socket is marked nonblocking and the requested operation would block.
POSIX.1-2001 allows either error to be returned for this case,and does not
require these constants to have the same value, so a portable application
should check for both possibilities.

      

Since my application needs to be portable, I have to do:

switch (errno):
  case EWOULDBLOCK:
  case EAGAIN:
    //do whatever
    break;
  case EINTR:
    //...

      

The problem is that for some platforms, EWOULDBLOCK and EAGAIN have the same meaning, so when I compile I get:

 connection.cxx:190:5: error: duplicate case value
 case EWOULDBLOCK:
 ^
 connection.cxx:189:5: error: previously used here
 case EAGAIN:
 ^

      

So, I thought I could use a macro macro that depends on whether EWOULDBLOCK and EAGAIN have the same meaning or not for the platform, add this line to the code, or omit it.

Any idea on how to write this macro?

+3


source to share


2 answers


Something like:

 #if EAGAIN != EWOULDBLOCK
      case EAGAIN:
 #endif
      case EWOULDBLOCK:

      

edit: however, if you have many switch statements, the macro will be better than conditional compilation. Something like:

 #if EAGAIN == EWOULDBLOCK
 #define MY_AGAIN EAGAIN
 #else
 #define MYAGAIN EAGAIN: case EWOULDBLOCK
 #endif

      

Then, to use it:

 case MY_AGAIN:

      



You will see that the colon is not part of the macro where it is called:

 case ---->MACRO GOES HERE<-----:

      

however in the second case, when it expands in the context of the original surrounding text:

 case EAGAIN: case EWOULDBLOCK:

      

which would be really ugly if written explicitly in your switch statement, but is perfectly legal C code.

+8


source


Do not use switch

, then; just use

if(errno == EWOULDBLOCK || errno == EAGAIN) {
    ...
}

      



The compiler will, of course, happily optimize this for a single test, if it is EWOULDBLOCK

in fact equal EAGAIN

.

+5


source







All Articles