CPP Constants

Working with Constants in C++

  1. A Literal Constant is a value typed directly into your program wherever it is needed.
    It is for example:
    int age = 39; // the number 39 cannot be changed
  2. A Symbolic Constant is a constant that is represented by a name, just as a variable is represented.
    For example:
    #define membersInEachGroup 12;
    members = groups * membersInEachGroup;
    const unsigned short int membersInEachGroup = 12;
    members = groups * membersOnEachGroup;
    The last one is typed an in many cases better to use then the first symbolic constant.
  3. A Enumerated Constant enable you to create new types and then to define variables of those types whose values are restricted to a set of possible values.
    For example:
    Source code Result
    #include <iostream>
    int main() {
      enum Months { jan, feb, mars, april, may, june,
        july, aug, sep, oct, nov, dec  };
      Months thisMonth= april;
      if (thisMonth == dec ||
        thisMonth == jan ||
        thisMonth == feb)
        std::cout << "I is Winter season!\n";
      else  if (thisMonth == mars ||
        thisMonth == april ||
        thisMonth == may )
        std::cout << "I is Spring season!\n";
      else  if (thisMonth == june ||
        thisMonth == july ||
        thisMonth == aug )
        std::cout << "I is Summer season!\n";
        std::cout << "I is Autumn season!\n";
      return 0;
    I is Spring season!

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.