Cleaning up my code

This is a discussion on Cleaning up my code within the C++ Programming forums, part of the General Programming Boards category; A single char is simply treated as an integral type and by making it const, we can use it as ...

  1. #16
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    A single char is simply treated as an integral type and by making it const, we can use it as a case label in a switch statement.
    I don't understand why it must be const.
    benforbes@optusnet.com.au
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  2. #17
    Registered User
    Join Date
    May 2003
    Posts
    161
    Originally posted by bennyandthejets
    I don't understand why it must be const.
    It's just the design of the switch statement. Each case label must have a constant value. By restricting the cases to constant values, it allows the compiler to make more aggressive optimizations on the jump table.

    Try this in your compiler:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      int one = 1;
      int two = 2;
    
      int val = 1;
    
      switch(val)
      {
      case one: cout << "one" << endl; break;
      case two: cout << "two" << endl; break;
      }
    
      return 0;
    }
    I get the following errors:

    $ g++ test.cpp
    test.cpp: In function `int main()':
    test.cpp:14: case label does not reduce to an integer constant
    test.cpp:15: case label does not reduce to an integer constant

    However, change it to this:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      const int one = 1;
      const int two = 2;
    
      int val = 1;
    
      switch(val)
      {
      case one: cout << "one" << endl; break;
      case two: cout << "two" << endl; break;
      }
    
      return 0;
    }

    And it compiles without errors.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proposal: Code colouring
    By Perspective in forum A Brief History of Cprogramming.com
    Replies: 28
    Last Post: 05-14-2007, 07:23 AM
  2. Explain this C code in english
    By soadlink in forum C Programming
    Replies: 16
    Last Post: 08-31-2006, 12:48 AM
  3. Updated sound engine code
    By VirtualAce in forum Game Programming
    Replies: 8
    Last Post: 11-18-2004, 11:38 AM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 0
    Last Post: 02-21-2002, 05:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21