By default at the beginning of the switch block

When viewing the code for the parser, for example. Parser.cpp inside clang / Parse clang compiler directory

switch (Close) { default: break; case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break; case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break; case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break; case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break; case tok::greatergreatergreater: LHSName = "<<<"; DID = diag::err_expected_ggg; break; } 

I see that default is at the beginning. Is there any reason to save it. Usually we keep default at the end, so I'm a bit confused.

+4
source share
2 answers

The order makes no difference if you enable break s.

As an aside, I like to put break just before each case or default . It is much easier to check the validity of this rule than to try to look at the end of each case statement.

 switch (Close) { break; default: break; case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break; case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break; case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break; case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break; case tok::greatergreatergreater: LHSName = "<<<"; DID = diag::err_expected_ggg; } 

You might find this easier to understand if you interpret break as "Don't get into this case from any other case." instead of "Do not get out of this case in any subsequent case."

In this layout it is very easy to see if there is a break and, therefore, force the writer (and reader) to ask themselves, β€œDo I want to continue here?”. All break line up beautifully, and this is very obvious if it is missing.

Clarification: there is no β€œmagic” in my answer. I just put my spaces in a manner that is more readable to me. And spaces don't matter, so I'm free to do this. A break at the very end of the switch is redundant. If absent, the compiler is not allowed to move to the top of the switch , as if it were some kind of while while . Equally, the redundant break at the very beginning of the switch does not change anything and must be accepted (and ignored) by the compiler.

+1
source

The only time I see the default question position is to do something like this, this is a Duff Device design and should probably never attempt on modern platforms. :)

 void copyAligned4Bytes(u32 *in, u32 *out, int numBytes) { assert((numBytes & 0x03) == 0); while(numBytes) { switch(numBytes) { default: *out++ = *in++; numBytes -= 4; case 12: *out++ = *in++; numBytes -= 4; case 8: *out++ = *in++; numBytes -= 4; case 4: *out++ = *in++; numBytes -= 4; } } } 

Ah, the joys of coding in C are as close to assembler as possible to get a specific type of jump table.

0
source

Source: https://habr.com/ru/post/1395105/


All Articles