And does each expression in the else if must test the same variable ? Please give example for the second question.
And can any expression be used for the IF expression ?
And in SWITCH statement, each case can have only one statement or more ? If we can put more than 1 statement, then what is the syntax for it ?
case 1:
printf("Blah Blah");
printf("Blah blah blah");
Or
case 1:
{
printf("Blah Blah");
printf("Blah blah blah");
}
Yes these are all silly question’s but I am still learning programming.
Thanks in advance.
if, else, “else if”
An
ifcan have zero or one associatedelseclauses. Examples:or
These take only a single statement. If you want to use multiple statements (and some people say it’s better to do this even if you only have one statement per
if/else), you have to use curly braces, like this:You can also nest
ifs:This is usually written in a more readable way, though:
You see, the
else ifis nothing special, it’s just another form of laying out a nestedif.Again, if you want more than one statement in there, you need to use curly braces:
switch/case
As for
switchstatements, there you don’t need curly braces. Note however that “cases fall through” which means that in this example all fourprintfs are actually executed:If you don’t want this (which is usually the case), you have to use an explicit
breakafter the code in eachcase:Blocks
By the way, the curly braces rule can be generalized: At every place where a single statement is allowed, you can also use something like
{ ... }, which is called a block. The advantage of using blocks is that you canif)case 3: { int x = 3; printf("%d\n", x); }.