Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C switch statement with non-compound statement use case? [duplicate]

Tags:

c

It is possible to write a C switch statement with a non-compound sub-statement:

int x = 2;
int y = 3;

int main()
{
    switch (x)
        y++; // ok

    switch (x)
        case 2: y++; // ok
}

Is there any use case for this? That is, is there ever a reason to use a non-compound sub-statement of a switch statement?

like image 990
Andrew Tomazos Avatar asked Nov 16 '13 16:11

Andrew Tomazos


People also ask

Can switch-case have 2 conditions?

You can use have both CASE statements as follows. FALLTHROUGH: Another point of interest is the break statement. Each break statement terminates the enclosing switch statement.

Can switch statements use doubles in C?

The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.

What will happen if the switch statement did not match any cases?

If the switch condition doesn't match any condition of the case and a default is not present, the program execution goes ahead, exiting from the switch without doing anything. Show activity on this post.

How many cases a switch statement can have?

Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.


2 Answers

The first switch block in the code doesn't do anything.

When switch statement expression is evaluated, the source code present until the occurrence of matching case label or default label, will be ignored. Hence it doesn't print statement "Before case" in the below program.

int x = 2;
int y = 3;

    int main()
    {
        switch (x)
        {
            y++; 
             printf("Before case");
         case 2:
            printf("In case 2");
            break;
         }

       return 0;
    }

Output:

In case 2
like image 121
bjskishore123 Avatar answered Nov 14 '22 23:11

bjskishore123


"Control passes to the statement whose case constant-expression matches the value of switch ( expression ). [...] Execution of the statement body begins at the selected statement and proceeds until the end of the body or until a break statement transfers control out of the body." (http://msdn.microsoft.com/)

I don't think the first switch does anything... When I compiled it, y was 4, which means it only incremented it once.

like image 42
Eutherpy Avatar answered Nov 15 '22 01:11

Eutherpy