Reputation:
error running this c program . i'm getting an error like" case label doesnot reduce to an integer constant ". help me in finding my errors . i'm a newbie to c, started it a few weeks ago.thanks in advance
#include<stdio.h>
main()
{ int a,b,c;
scanf("%d",&c);
if (c<5) {
c==a ;
}
else { c==b;
}
switch (c)
{
case a:
printf ("statement1");
break;
case b :
printf(" statement2");
break;
}
}
Upvotes: 2
Views: 8524
Reputation: 113507
I corrected your code. Please try it and give me a feedback:
#include <stdio.h>
using namespace std;
int main()
{
int a,b,c;
scanf("%d",&c);
if (c<5)
{
a = c; //here you will use "=" because you want to a became c
}
else
{
b = c; //here you will use "=" because you want to b became c
}
/*--------IF-------------*/
if(c==a) //here is a condition. you will use "=="
{
printf("statement1");
}
if(c==b) //here is a condition. you will use "=="
{
printf ("statement2");
}
/*--------SWITCH-------------*/
switch (c)
{
case 1: //if c is 1
case 2: //if c is 2
case 3: //if c is 3
case 4: //if c is 4
printf("statement1"); //"statement1" will appear
break;
default: printf("statement2"); //if c >= 5 "statement2" will appear
}
return 0;
}
Upvotes: 2
Reputation: 105
are you assigning integer c to a or b? you should use = not == and put a or b in the left side of the assignment, not the right side. Like this:
if (c<5) {
a=c;
}
otherwise, if a and b are integers with an assigned value, you can assign one or the other value to c, like:
if (c<5) {
c=a;
}
keep in mind switch..case sentences in C can only switch between (compare) integer values (cases), that's why you're getting the error.
Upvotes: 0
Reputation: 143172
2 problems:
the values for your case labels need to resolve (ie end up) as integer values for the case
-statement to work. If you want to drive the statements in the case
based on the value of variable c
and comparing it with a
and b
, you might want to consider an if
-statement instead.
You need to do assignments =
rather than boolean comparisons ==
here
c==a
probably want
c = a
(same applies to c==b
) -
in fact, are you sure this is the right order, and you don't want the reverse a = c
? This seems more likely looking at your code segment.
Upvotes: 2
Reputation: 182794
In C, which you seem to be calling c#
for some reason, case
labels must be integer constants.
6.8.4.2-3
The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion.
Not sure if this is what you want, but you could try:
switch (c) {
case 'a':
break;
case 'b':
break;
}
Otherwise, maybe you want
if (c == a)
/* ... */
else if (c == b)
/* ... */
else
/* ... */
As side note, you probably want c=a
instead of c==a
.
Upvotes: 6