I am trying to understand the switch statement in C (I am using gcc from Ubuntu v16.04). I am able to understand its semantics, but have the following 2 questions about its syntax:
I have noticed after reading a few examples of usage of switch statement that the symbol after case is sometimes enclosed in ''
and sometimes it isn't.
eg: case 1
or case 'a'
.
I checked the Linux manpage for the switch statement (https://linux.die.net/man/1/switch) and there they have not used ' ' for a string. So I don't know what to do.
Sometimes the block of code within a single case is enclosed in a { }
and sometimes it is not. I had read before that multi-line statements need to be enclosed in a { }
, but not necessarily for single-line statements as in a for loop,while loop with single line statements etc. But sometimes a case statement has 1 line of code (for eg a *= 5;
) followed by break
statement (so total 2 statements) and yet both lines are not enclosed in { }
. The Linux manpages haven't mentioned this. Can someone clarify this?
(1) 'a' is ascii value 97. Ascii is a standard way of encoding characters and it's used in many other languages as well. Essentially, each character is represented as a numerical value. So when you have:
...
case 'a':
...
you are actually executing the code below the case if the switch variable is equal to 97. In your example:
case '1':
checks if the switch variable is equal to char '1', which is ascii value 49.
(2) Enclosing a case statement with braces changes the scope of the variables between the braces. Consider the following example:
switch (sw) {
case 1:
int b = 2;
sw += b;
break;
case 2:
int b = 3;
sw += b;
break;
default:
break;
}
This is because in case 1 and case 2, you are instantiating an integer called "b". Since both case statements are in the same variable scope (the switch statement's scope), the compiler gives you an error since you are instantiating a variable with the same name and type twice. Now consider the code below:
switch (sw) {
case 1: {
int b = 2;
sw += b;
break;
} case 2: {
int b = 3;
sw += b;
break;
} default: {
break;
}
}
This code compiles. By enclosing each case's code in braces, you are giving each case its own variable scope, where it could redefine the same variable once in each scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With