C Programming - Control Instructions - Discussion

6. 

Point out the error, if any in the program.

#include<stdio.h>
int main()
{
    int P = 10;
    switch(P)
    {
       case 10:
       printf("Case 1");

       case 20:
       printf("Case 2");
       break;

       case P:
       printf("Case 2");
       break;
    }
    return 0;
}

[A]. Error: No default value is specified
[B]. Error: Constant expression required at line case P:
[C]. Error: There is no break statement in each case.
[D]. No error will be reported.

Answer: Option B

Explanation:

The compiler will report the error "Constant expression required" in the line case P: . Because, variable names cannot be used with case statements.

The case statements will accept only constant expression.


Ansar said: (Mar 5, 2012)  
In case 10 there is no break statement. So I think option "c" is also correct.

Shubham Saurabh said: (Apr 29, 2012)  
In a case using break; is optional. @ansar.

Karthik said: (May 4, 2012)  
While executing no error is reported.

Tanya said: (Jul 7, 2013)  
Why can't we use variable names in case statement?

Aniruddh said: (Aug 9, 2013)  
That's true, P can't be used as case expression here, executed code, error reported.

Zeeshan said: (Jan 5, 2014)  
I feel that if p is a char type then characters can be used in switch statement. The explanation is not justified.

Hardeep said: (Sep 15, 2014)  
Actually here p is variable we never provide variable directly to case so it must be like following that it never generate error.

Case 'P':.

Edgar Mamani said: (Oct 7, 2014)  
We can use #define directive, but we can't use "const int Q".


#include<stdio.h>
#define OP 30

int main()
{
int P = 10;
const int Q = 40;

switch(P)
{
case 10:
printf("Case 1");

case 20:
printf("Case 2");
break;

/*case P:
printf("Case 2");
break;*/

case OP:
printf("Case 3");

/*case Q:
printf("Case 4");*/
}
return 0;
}

Nishmitha Balakrishna said: (Oct 24, 2018)  
Why it won't accept variable name? Please explain the reason.

Sayali Worlikar said: (Nov 23, 2018)  
Varialble name can be used but should be written as 'P'.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.