I need to know why we are using colon on keyword case
in c programming and not semicolon?
/*valid statement*/
case 1:
do this;
case 2:
do this;
/*why is invalid to write */
case 1;
do this;
case 2;
do this;
help me please
Why a case
line shouldn't be ended with a semicolon
In C-based languages, the semicolon has a specific function as the 'statement terminator'. This means that a semicolon marks the end of a specific statement of code, and the start of another. For more info on this see this quora post.
Therefore if you had a semicolon after each case
line, the compiler would interpret them all as separate, individual statements. It would be like writing:
do case 1;
do this;
do case 2;
do this;
The compiler sees these as individual, 'normal' lines of code. It will probably then fail to compile, because the case
keyword is specifically reserved only for use within switch
statements.
As to why the :
character was selected for this particular purpose: as Luca_65 mentioned the case is hiding a goto
label statement. The colon is used in C to label a section of code, and this syntax has followed through to it's derivative languages.
As Bobby Speirs noted, that character was probably originally chosen due to the colon's similar meaning in English grammar.