C++ Variables, Literals, and Constants

What is a variable?

Variable is the name given to a memory location where data can be stored and whose value can be changed during the program. Each variable in C++ has a specific data type that determines the size of the variable’s memory and the range of values that can be stored within that memory.

What are the rules to define variables?

The rules are as follows:

  1. Variable names can be composed of alphabets, digits, and underscore.
  2. Variable names must begin with either an alphabet or an underscore. 

Note: It should not start with a digit.

  1. Whitespace and special characters are not allowed within a variable name.
  2. Reserved keywords cannot be used as variable names.
  3. Variable names are case-sensitive.

How to declare a variable?

A typical variable declaration is of the form:

data_type  variable_name;
For Example: int rollNo;
 

Types of variables

  • Local Variables: Local variables are declared inside the function, method, or block. Their scope lies within the block where they are declared, that is we can access these variables only inside the block. It is mandatory to initialize them otherwise the compiler does it itself and gives it a garbage value.

Code:

C++ Code

 //C++ Program to demonstrate local variables.
#include <iostream>
using namespace std;

class Student {
  public:
    void studentRollNo() {
      int rollNo = 20; //local variable rollNo
      rollNo += 5;
      cout << "The rollNo is: " << rollNo;
    }
};

int main() {
  Student s;
  s.studentRollNo();
  return 0;
}

Output:

The rollNo is: 25

  • Instance Variables: Instance variables are declared in a class but outside the functions, methods, and other blocks. These variables get memory when an object of that class is created and are destroyed when the object gets destroyed. It is not mandatory to initialize them. Access specifiers can also be used but if we don’t specify them then the default is private.

Code:

C++ Code

 //C++ Program to demonstrate instance variables.
#include <iostream>
using namespace std;

class Student {
  int rollNo; //instance variable
  public:
    void set_data() {
      rollNo = 20;
    }

  void display() {
    cout << "The rollNo is: " << rollNo;
  }
};

int main() {
  Student s;
  s.set_data();
  s.display();
  return 0;
}

Output:

The rollNo is: 20

  • Static Variables: Static variables are similar to instance variables but are common to every object of the class which means only one copy of the variable is created irrespective of how many numbers of objects are created in the program. They are declared using a static keyword before the data type. They get memory at the start of the program and get destroyed when the program ends. It is mandatory to initialize them and it is done outside the class.

Code:

C++ Code

//C++ Program to demonstrate static variables.
//Auto incrementation of roll no using static variables.
#include<iostream>
using namespace std;

class Student {
  static int id; // static variable
  int roll_no;
  char name[50], course[20];
  public:
    void set_data();
    void display();
};

int Student::id = 1000;
void Student::set_data() {
  roll_no = ++id;
  cout << "Enter name of student: ";
  cin >> name;
  cout << "Enter course: ";
  cin >> course;
}

void Student::display() {
  cout << "\t" << roll_no << "\t" << name << "\t" << course << endl;
}

int main() {
  Student s[100];
  int n, ch, i;
  do {
    cout << "1-Enter details of students\n2-Display list\n3-Exit\n";
    cout << "Enter your choice: ";
    cin >> ch;
    switch (ch) {
    case 1:
      cout << "Enter number of students: ";
      cin >> n;
      for (i = 0; i < n; i++) {
        s[i].set_data();
      }
      break;
    case 2:
      cout << "---------------DETAILS OF STUDENTS---------------" << endl;
      cout << "\tROLL_NO\tNAME\tCOURSE\t\n";

      for (i = 0; i < n; i++) {
        s[i].display();
      }
      break;
    case 3:
      exit(0);
      break;
    default:
      cout << "Enter valid choice!" << endl;
    }
  } while (ch != 3);
  return 0;
}

Output:

1-Enter details of students
2-Display list
3-Exit
Enter your choice: 1
Enter number of students: 3 3
Enter name of student: Aakriti
Enter course: B.Tech
Enter name of student: Akshita
Enter course: M.Tech
Enter name of student: Ankit
Enter course: M.Tech
1-Enter details of students
2-Display list
3-Exit
Enter your choice: 2
—————DETAILS OF STUDENTS—————
ROLL_NO NAME COURSE
1001 Aakriti B.Tech
1002 Akshita M.Tech
1003 Ankit M.Tech
1-Enter details of students
2-Display list
3-Exit
Enter your choice: 3

Literals and Constants

What are literals?

Literals are numbers/letters that indicate the value of a constant.

What are the types of literals?

There are two types of literals:

  1. Numeric Literal
  2. String/Character Literal

Numeric Literal: 

Numeric literals are again of two types:

  1. An integer literal: An integer literal is a signed/unsigned whole number. C++ language allows 3 types of integer literals:

i) Decimal Integer Literal: It consists of a sequence of digits and should not start with zero. 

Example:

25

ii) Octal Integer Literal: It consists of a sequence of digits starting with zero.

Example:

031 

iii) Hexadecimal Integer Literal: It consists of a sequence of digits starting with 0x.

Example:

0x19

Note: The default integer literal in C++ is decimal.

  1. Real/Floating Point Literals: Any signed or unsigned number with a fractional part is called a real or floating point literal.

Example:

0.254

String/Character Literal

Any string of characters enclosed in quotes is called string/character literal. String/character literal is of two types:

  1. Single Character String Literal: Any letter/character enclosed in single quotes is a single character string literal.

Example:

‘u’
  1. String Of Characters Literal: Any string of characters consisting of letters, digits, and symbols enclosed in double quotes is a string of characters literal.

Example:

“Sum=”

What are constants?

Constants are variables that cannot be modified or changed by the program once their value is defined.

How can we define a constant?

There are 2 ways to define a constant:

  1. Using #define preprocessor directive

Syntax:

#define identifier value

Example:

#define LENGTH 20
  1. Using a const keyword

Syntax:

const data_type variable = value;

Example:

const int LENGTH=20;

Note: 

So are constants and literals the same? 

Answer: No, they are not the same. Let’s consider an example to make things more clear.

const int LENGTH = 20;

Here the value LENGTH is a constant and 20 is literal.

The major difference is that constant may have an address in the memory whereas literal never has an address.

Special thanks to Aakriti Singh for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article