Constants

Constants are expressions with a fixed value.

 

  • Literals
    • Specific values assigned to an identifier
    • Numerical
      • Integer
        • myVar = 17 ;
      • Floats
        • yourVar = 32.548 ;
    • Characters
      • Single character between 'single quotes'
      • Important to use quotes, otherwise it could refer to another variable called D
      • myChar = 'D' ;
    • Strings
      • String of characters between "double quotes"
      • myString = "Selenium" ;
    • Booleans
      • TRUE or FLASE
  • Defined
    • Used by the preprocessor
    • Syntax: #define IDENTIFIER value
    • Note, no semi-colon ;
    • Common practice is to define the identifier in UPPERCASE
    • #define PI 3.14159
#include <iostream>
using namespace std ;

#define HI "Hello, World!"

int main () {

	cout << HI << endl ;

	return 0;
}

 

  • Declared
    • Utilises the const keyword
    • Cannot be changed after they've been defined
    • Common practice is to define the identifier in UPPERCASE
#include <iostream>
using namespace std ;

int main () {

	const int LENGTH = 6 ;

	cout << "6 squared = " << LENGTH * LENGTH << endl ;

	return 0;
}

Leave a Reply