-1

I have got a doubt with switch-case statements. I read that 'const variable' can be used in switch cases.

However following program is giving me an error case label does not reduce to an integer constant

#include <stdio.h>
int main()
{
    int const var = 3;
    int num=3;
    switch (num)
    {
        case var:
            printf("constant var");
            break;
    }
}

Where am I making the mistake ?

Mariappan Subramanian
  • 9,527
  • 8
  • 32
  • 33
  • 2
    I'm afraid `case var` really has to be `case 3`. Or use a `#define VAR 3` and `case VAR` instead. –  Mar 20 '17 at 05:02
  • If you want your current semi-flexibility, it's back to if statements. –  Mar 20 '17 at 05:03
  • Hi Evert, Thanks for the reply . If you go through this link, http://www.c4learn.com/c-programming/c-switch-case-rules/ , It says const variables can be used in switch case statments – Mariappan Subramanian Mar 20 '17 at 05:05
  • Works fine for me (clang-602.0.49) but apparently not portable. – Arash Mar 20 '17 at 05:07
  • @Arash When I compile with `clang -Weverything`, I get the following warning: "warning: expression is not an integer constant expression; folding it to a constant is a GNU extension [-Wgnu-folding-constant]". Funnily enough, `gcc` doesn't allow this by default. –  Mar 20 '17 at 05:10
  • 1
    @Mari So it's a GNU extension, not something from the standard. Have a read through section 6.6 of the (officially draft) [C11 standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), which deals with constant expressions. The key take-away seems to be that "2. A constant expression can be evaluated during translation rather than runtime", and `const` is less strict in C than e.g. in C++. –  Mar 20 '17 at 05:11
  • 1
    Do send feedback to that site asking them to fix the wrong information. – Sami Kuhmonen Mar 20 '17 at 05:12
  • @Ever. Yes. I had the same warning. – Arash Mar 20 '17 at 05:13
  • It looks like it works in C++ but not in C ... – AntonH Mar 20 '17 at 05:13
  • Thanks a lot Evert and Arash ! – Mariappan Subramanian Mar 20 '17 at 05:14
  • @AntonH This is why C != C++. See also my previous comment, last line. –  Mar 20 '17 at 05:14
  • Hi Evert ! Please post your comment in the answer section. So that I can accept it and close the Q – Mariappan Subramanian Mar 20 '17 at 05:17
  • You might ahve read about C++, which is a different language. C does not support symbolic constants other than _enum constants_. Your title already includes the answer: "Constant **Variable** …" – too honest for this site Mar 20 '17 at 05:23
  • "where am I doing a mistake" - you're doing a mistake by not entering your error message into google and opening the stack overflow QA that is the first search result. – Antti Haapala -- Слава Україні Mar 20 '17 at 05:32

5 Answers5

2

In C. all case labels must be compile time constants and const variables are read-only, but no constants. So, you can do this

#define var 3

instead of

int const var = 3;
msc
  • 33,420
  • 29
  • 119
  • 214
  • Hi rsp, Thanks for the reply. Please refer to the 'Rule-13' in the following link http://www.c4learn.com/c-programming/c-switch-case-rules/ – Mariappan Subramanian Mar 20 '17 at 05:09
  • 1
    Actually it does not even this. It is a guarantee **by the programmer** not to change the object. Whether it is read-only is implementation-specific. Inside a `struct`, e.g. with other non `const` qualified members, (almost) all implementations store the object in writable memory. – too honest for this site Mar 20 '17 at 05:31
  • @Mari: Why should one refer to something non-autoritative of unknown quality? The standard is enough and the only relevant reference. – too honest for this site Mar 20 '17 at 16:00
1

according to the C standard(N1570 Committee Draft):

6.8.4.2 The switch statement

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. There may be at most one default label in a switch statement. (Any enclosed switch statement may have a default label or case constant expressions with values that duplicate case constant expressions in the enclosing switch statement.)

6.6 Constant expressions define integer constant expression

An integer constant expression117) shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator.

zzn
  • 2,376
  • 16
  • 30
  • What is the meaning of sentence inside the parenthesis "Any enclosed switch statement may have a default label or case constant expressions with values that duplicate case constant expressions in the enclosing switch statement" – Rajesh Feb 14 '18 at 04:39
0

A variable is contain the constant value, while making a constant variable it doesn't change the objective of a variable. It always be a variable, and switch case takes only constant values not variables.

#include <stdio.h>
int main()
{
    int const var = 3;
    int num=3;
    switch(num)
           {
           case var: // use a constant value(Not variable) here
                   printf("constant var");
                   break;
            }

}

Satrughna
  • 93
  • 2
  • 14
  • 2
    "It always be a variable": this (I think) is key. It's still a variable indeed, but you told the compiler you won't (and thus can't) change it. –  Mar 20 '17 at 05:13
  • @Mari Please refer this [link](http://stackoverflow.com/questions/14069737/switch-case-error-case-label-does-not-reduce-to-an-integer-constant) awefully described here. – Satrughna Mar 20 '17 at 05:27
0

Your switch case must have condition like this, instead of var

#include <stdio.h>
int main()
{
int const var = 3;
int num=3;
switch(num)
       {
       case 3:
               printf("constant var");
               break;
        }

}

Instead use #define var 3 like:

#include <stdio.h>
#define var 3
int main()
{
//const int var = 3;
int num=3;
switch(num)
       {
       case var:
               printf("constant var");
               break;
        }
return 0;
}

In your code, switch case is looking for var constant instead of case 3

Bidisha Pyne
  • 543
  • 2
  • 13
-1

When you are trying to switch a case, the switching generally depends on the value which is assigned to the variable (in your case the variable is num whose value is 3). The value of this variable can even change. There is no rule that a variable whose value is getting switched (num) should be a constant integer. Switch cases are not meant for hard coded values. Depending upon the value of the variable that particular switch case will be executed and the value can even change (in you code it does'nt, because you have hard coded it as 3) Please try this code

 #include <stdio.h>
 int main()
 {
   //int const var = 3;
   int num=3; 
   switch(num)
   {
   case 3:    //If the value of num is "3", then execute this case.
           printf("constant var");
           break;
   case 4:    //If the value of num is "4", then execute this case.
           printf("Test case");
           break;
   default: //If the value of num is anything other than "3" and "4", then execute this case
            printf("Default case");
            break;
    }
  return 0; //This should be included as you are returning an integer
  }

Inside the switch case, you are supposed to mention the value (of num) depending on which the case will be executed. Also, please note that when you have declared the return type of your main() as integer, it is better you include a return 0 in the end. After you run the code with num=3, please try the same code with num=4 and num=5.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Coding Ninja
  • 114
  • 12
  • Please explain why a down vote. Is my answer not upto the mark ? – Coding Ninja Mar 20 '17 at 05:27
  • The switch-selector expression (there need not be a variable, any integer expression will do actually) is not in question. You miss the point about the case-labels. – too honest for this site Mar 20 '17 at 05:28
  • Before asking to comment you should wait for some time to let people write the comment. Otherwise you might not get a comment at all next time. – too honest for this site Mar 20 '17 at 05:28
  • I really don't understand ..... his logic framing in the code is completely wrong and I corrected it. He has taken one variable and is switching it with another value and I have corrected it. – Coding Ninja Mar 20 '17 at 05:31
  • Hard coding a variable is not the purpose of a switch case. He has hard coded the value because he is a starter, just to do some hands on. The way he has framed his code's logic is completely wrong and your comment shows how well you have checked it before down voting. – Coding Ninja Mar 20 '17 at 05:34
  • OP did exactly the opposite of hard-codinmg the case-label. Which was the problem. In fact, your code does. But you concentrate on the selector expression, which is not in question - did you even read my comment? – too honest for this site Mar 20 '17 at 05:40
  • The issue is not about hard coding, but it is about logic framing. He is switching the value of `num` and checking whether it becomes `var` or not That's the reason he is getting this error : ** case label does not reduce to an integer constant. ** When does `num` become `var` ? Can you please explain ? – Coding Ninja Mar 20 '17 at 06:02
  • Read the other answers and comments. They should make it clear! Maybe you have the right in mind, but from what you write in your comments (even more than in your answer), it is completely unclear what you mean. Last time: this is not a single bit about `num`. Read the standard. – too honest for this site Mar 20 '17 at 15:57