C Programming - Control Instructions - Discussion
Discussion Forum : Control Instructions - Point Out Errors (Q.No. 6)
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;
}
Answer: Option
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.
Discussion:
10 comments Page 1 of 1.
Sayali worlikar said:
7 years ago
Varialble name can be used but should be written as 'P'.
Nishmitha Balakrishna said:
7 years ago
Why it won't accept variable name? Please explain the reason.
Edgar Mamani said:
1 decade ago
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;
}
#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;
}
Hardeep said:
1 decade ago
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':.
Case 'P':.
Zeeshan said:
1 decade ago
I feel that if p is a char type then characters can be used in switch statement. The explanation is not justified.
Aniruddh said:
1 decade ago
That's true, P can't be used as case expression here, executed code, error reported.
Tanya said:
1 decade ago
Why can't we use variable names in case statement?
Karthik said:
1 decade ago
While executing no error is reported.
Shubham saurabh said:
1 decade ago
In a case using break; is optional. @ansar.
ANSAR said:
1 decade ago
In case 10 there is no break statement. So I think option "c" is also correct.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers