Consider this C construct that checks for errors before doing actual work:
int function(struct Context *context,struct Connection *conn)
{
int retval;
switch(0)
{
case 0:
retval = BUFFER_INACTIVE;
if(conn->mSocket == -1)
break;
retval = BUFFER_FULL;
/* Is there enough room to add ? */
if((context->mMaxBufferSize - conn->mSendPacketLength) < aPacketLength)
break;
/* Is the send packet buffer half sent? */
if(conn->mSendPacketLength > 0 && conn->mSendPacketPos != conn->mSendPacket)
break;
/* Do some work here */
retval = BUFFER_DONE;
}
/* Do some things before returning */
printf("%d",retval);
return retval;
}
Would you consider this a being readable? Would the alternatives, using goto or stacked if() be better?
I’ve never seen the switch solution, but I’ve done stuff like this:
But what’s the real difference between that and this:
The first is just the second one rewritten to avoid using the keyword
goto, and I’d argue that thegotosolution is more readable. It took me a while, but I’ve managed to convince myself thatgotos are not always evil.In the end, I prefer just using
ifstatements if possible since it makes the code more readable, butgotos if necessary.