"Success has many fathers, while failure is an orphan."
- (Proverb)
5.
Which of the following errors would be reported by the compiler on compiling the program given below?
#include<stdio.h>
int main()
{
int a = 5;
switch(a)
{
case 1:
printf("First");
case 2:
printf("Second");
case 3 + 2:
printf("Third");
case 5:
printf("Final");
break;
}
return 0;
}
[A].
There is no break statement in each case.
[B].
Expression as in case 3 + 2 is not allowed.
[C].
Duplicate case case 5:
[D].
No error will be reported.
Answer: Option A
Explanation:
Because, case 3 + 2: and case 5: have the same constant value 5.
Is variable addition is allowed in case statements ?
Raj said:
(Thu, Sep 22, 2011 05:30:07 PM)
Because case 3+2 is equal to case 5. So ambiguity occurs.
Hyma said:
(Wed, May 16, 2012 10:08:27 AM)
Yes addition is allowed in case statements but case 3+2 is equal to case 5 so ambiguity is occurs.
Knight said:
(Sat, May 19, 2012 11:37:52 AM)
Addition, multiplication, division are allowed in case statement but both the operand should be constant, operation is performed at compile time, for this case compiler get confused while choosing case 5 (ambiguity). So it will raise compile time error.