-5

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

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Husmukh
  • 66
  • 5

4 Answers4

1

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.

0

The colon makes more sense from an English writing point of view, which makes the code easier to read.

Think of it like telling the computer the following:

In case the number is 1, you should do these things: 
    Thing 1;
    Thing 2;
    Thing 3;
Bobby Speirs
  • 667
  • 2
  • 7
  • 14
0

C switch hide a goto to the label equal to the value under test.

Luca_65
  • 123
  • 9
0

Quoting C11, chapter §6.8.1

A case or default label shall appear only in a switch statement.

So, a case is a labeled-statement.

the prescribed format of a labeled statement is given by

labeled-statement:
identifier : statement
case constant-expression : statement
default : statement

Regarding the choice of the :, this is in regards to the assembly syntax, where : is used to identify a designated block of statement.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261