Free Courses

Keywords in C++

Learn about Keywords in CPP

Updated - 16 Mar 202211 mins readPublished : 20 Jan 2022
Published : 20 Jan 2022
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

Keywords in C++ are the collection of reserved words. These are written in lower cases and have a special meaning defined by the compiler. There are 95 keywords in C++, of which around 30 are unavailable in the C language. Keywords are always used for a special purpose in a program, but we can't use them as variable or function names. Some examples of Keywords in C++ are break, int, void, public, private, auto, return and many more.

Scope

  • This article defines different types of Keywords present in C++ and how they differ from C++ Identifiers.
  • We also learn about types of qualifiers in C++ using examples and their syntax. For better understanding, we illustrate all these using C++ programs.

Tokens in C++

Like living cells in the human body are the smallest possible units of life, we have tokens in C++, which are the smallest building blocks of a program.
Tokens in C++ can be classified as:

  • Keywords
  • Identifiers
  • Constants
  • Operators
  • Strings

In this article, we will primarily learn about keywords, their types, and syntax and compare them with C++ Identifiers.

Keywords in C++

Keywords in C++ are the collection of reserved words. These are written in lower cases and have a special meaning defined by the compiler. We can’t use them to declare variable names or function names.

Example:

We can declare a variable 'nums' with any value, but we can't use keywords for this purpose.

int nums = 10;  // Here, nums is a variable and hence, it will store value 10
int return = 10; // Wrong statement, return is a keyword not a variable

Different types of Keywords in C++

There are a total of 95 Keywords in C++. Some of them are defined below:

autoboolbreakcasecatchcharclass
constcontinuedoubledefaultdeleteelseenum
explicitfriendfloatforintlongmutable
newoperatorprivateprotectedpublicregisterreturn
structswitchshortsizeofstaticthistypedef
throwtruetryunionvirtualvoidwhile
  • auto - It is used to deduce the data type of an expression, and in general, we don't need to specify the data type. Still, we can commonly use the auto keyword, which will automatically initialize the variable accordingly.
// C++ Syntax Illustration:
int num = 10;
string firm = "Firm";

// These can be modified as: (without knowing data - type).
auto num = 10;
auto firm = "Firm";
  • bool - It is used to define the data type and nature of the object, whether true/false.
  • break - It terminates a switch statement or any loop.
  • case - It is explicitly used for switch statements to support different situational cases.
  • catch - It specifies actions to be taken when an exception occurs during the program compilation.
// C++ Syntax Illustration:

// After the try block throws an exception, the catch block is executed.
catch (int num) {
  cout<<"Error in the program!";
}
  • char - It is used to define character objects.
  • class - It is used to declare a user-defined structure that encapsulates data members or functions.
  • const - It defines objects whose value will not change throughout program execution.
  • continue - It transfers control to the start of a loop.
  • default - It handles expression values in a switch statement that are not handled by the cases.
  • delete - It is used to deallocate the memory of an object.
  • double - It is used to define floating-point numbers.
  • else - It is used mainly in if-else program statements.
  • enum - It is used to define and declare user-defined data types.
  • explicit - It is used for single argument constructors that can be used in typecasting.
  • float - It is used to define floating-point numbers.
  • for - It is used in (for loop statements) to achieve repetitive control over encapsulated statements.
  • friend - Classes with the friend keyword can access the private data of members of a class.
  • int - It is a fundamental data type used to define integer objects.
  • long - It is used to define 32-bit int numbers.
  • mutable - If we have a constant object and declare it mutable, its value can be changed at any time during compilation and runtime.
  • new - It is used to allocate memory to an object in a program.
  • operator - It is used to overload a c++ operator with a new declaration.
  • private - It is used to declare class members which are not visible outside the class.
  • protected - It is used to declare private class members except for the derived classes.
  • public - It is used to declare class members that should be accessible outside the class.
  • register - Frequently used objects are kept inside registers.
  • return - It is used to return an object when we call a function to perform some tasks.
  • short - It is used to define a 16-bit int number.
  • sizeof - It returns the size of an object in bytes.
  • struct - It is used to declare new types containing data and member functions.
  • static - The originality of an object-defined static exists throughout program execution.
  • switch - It is used specifically for switch statements.
  • this - It is a pointer that points to an object or an instance of a class created.
  • throw - It is used to generate exceptions during the compilation of programs.
  • true - It is a boolean value, same as '1', resulting from an operation performed.
  • try - It indicates the start of the exception handling block.
// C++ Syntax Declaration:

// Try block throws an exception for catch block if requirements are not met.
try {
  int nums = 20;
  if (nums >= 22) {
    cout << "Program Executed!";
  } else {
    throw (nums);
  }
}
  • typedef - It is used for user-defined data types and acts as an alias for existing data types.
  • union - It can store only one type of data member at a given time.
  • virtual - It declares a class member function as virtual that a derived class will redefine.
  • void - It refers to the absence of a data type or function parameters list.
  • while - It is used to start a while statement and end a do-while statement.

List of C++ Keywords not available in C Language

There are a total of 30 Keywords in C++ which are not available in C language, illustrated below:

asmboolclasscatchconst_castdelete
dynamic_castexplicitfriendfalseinlinemutable
namespacenewoperatorprotectedpublicprivate
reinterpret_caststatic_casttemplatethrowtypenametrue
typeidthistryusingvirtualwchar_t

Type Qualifiers in C++

Type Qualifiers in C++ are applied to already defined data types and don't change the meaning of variables. Instead, they provide users with some extra information about the properties of the variable. For example - If we use a const qualifier against an integer variable, it means the value is constant in the memory, and further, we can't change it.

const int age = 20;
age = 30; // Error, constant integer value age can't be modified.

These type qualifiers in C++ can be classified as:

Const

Const qualifier defines that the variable is constant. We can't change or modify the value; if we try to do so, it will give a compile-time error.

Syntax for const type qualifier:

const <data_type> <variable_name> = <value_assigned>;

Example:

const string name = "Mayank";  
name = "Jain";

It will give a compile-time error as we try changing a constant variable - 'name.'

Volatile

A volatile object or a variable can be changed at any time in the program. For example, a variable declared as volatile can be updated using a system clock or even by reference to another program.

Syntax for volatile type qualifier:

volatile <data_type> <variable_name> = <value_assigned>;

Example:

int result;
result++; 

Here, the value is copied from memory to the CPU registers, and operations are performed.

volatile int words;
words++; 

The value is not copied from memory to the CPU registers as volatile is present.

Mutable

Mutable type-qualifier can make const-class members (constant) modifiable. In simple words, once a member is declared mutable, we can change its value anytime in the program code, even if the object created is const-type.

Syntax for mutable type qualifier:

mutable <data_type> <variable_name> = <value_assigned>;

Example:

class Test {
  public:
    Test(): xx(10), yy(20) {};
    mutable int xx; // Can be modified later
    int yy;
};

int main() {
  const Test obj; // Default constructor called, xx = 10 and yy = 20;
  obj.xx = 300; // Correct modification as xx is mutable.
  obj.yy = 200; // Error.
}

Restrict

Restrict type qualifier is used as a pointer but doesn’t provide any functionality to the code. Compilers can optimize the code in presence of restrict keyword.

Example:

If we are using restrict with a pointer itr, it means itr is the only way to access the object pointed by it, and there is no other alternative pointer to access the same object. Hence, the compiler doesn't need any additional checks.

C++ Program to understand Type Qualifiers:

In this program, we will understand the use of const, mutable and volatile type-qualifiers. Here, non-const num is declared 0, so its value can be changed. num1 is const-type, and changing its value will produce a compile-time error. num2 is declared with a volatile qualifier; hence, its value can also be changed at any time. In a non-static class Test, variable yy is declared mutable; hence, even if we create a const object of this class, we can always modify the value of variable yy.

#include <bits/stdc++.h>

using namespace std;

class Test {
  public:
    Test(): xx(10), yy(20) {};
    int xx;
    mutable int yy;
};

int main() {
  int num = 0; // Non-const object
  const int num1 = 0; // Const object
  volatile int num2; // Volatile object

  num = 1; // Non-const objects can be changed.
  //num1 = 2;  // Error as const variables can't be modified

  const Test obj;
  // obj.xx = 20; // Error as obj is constant object and xx was not declared as mutable.
  obj.yy = 100; // Mutable objects are modifiable.
  cout << " num: " << num << endl << " num1: " << num1 << endl << " num2: " << num2 << endl << " xx: " << obj.xx << endl << " yy: " << obj.yy;
  return 0;
}

Output:

 num: 1
 num1: 0
 num2: 0
 xx: 10
 yy: 100      

Identifiers in C++

Identifiers in C++ are short and informative names uniquely identifying C++ variables or function names. They are user-defined words. We can't use keywords as identifiers because keywords are pre-defined reserved words.

Difference between Keywords and Identifiers

  • Keywords should be in lower cases always, but Identifiers can be both in upper and lower cases.
  • Keywords can contain only alphabets, whereas Identifiers can contain alphabets, numeric digits, underscores, and special characters.
  • Keywords are pre-defined reserved words, whereas identifiers are user-defined words used to identify variables uniquely.
  • Some examples of valid Keywords: double, int, auto, char, break. Some examples of valid Identifiers: Test, Scaler_Academy, count1.

C++ Program to illustrate the use of Keywords:

Here is an example involving various keywords. We have used switch statements for multiple cases as input to print result values. Here as the input value is 2 in the program, hence "int keyword" will be printed.

#include <bits/stdc++.h>

using namespace std;

int main() {
  int n = 2;

  switch (n) {
  case 1:
    cout << " using namespace" << endl;
    break;
  case 2:
    cout << " int keyword" << endl;
    break;
  case 3:
    cout << " switch case" << endl;
    break;
  case 4:
    cout << " break default" << endl;
    break;
  case 5:
    cout << " return" << endl;
    break;
  default:
    cout << " Enter valid number!!" << endl;
  }
  return 0;
}

Output:

 int keyword     

C++ Program to illustrate the use of Identifiers:

In this program, we are initializing two valid identifier variable names, i.e., scaler_academy and count1, and thus, printing their result values.

//C++ program to illustrate the use of identifiers

#include <bits/stdc++.h>
using namespace std;

int main() {
  // Use of underscore symbol and numeric digit.
  int scaler_academy = 1; // valid identifier.
  int count1 = 2000; // valid identifier.

  cout << " Identifier result1 is: " << scaler_academy << endl;
  cout << " Identifier result2 is: " << count1;
  return 0;
}

Output:

 Identifier result1 is: 1
 Identifier result2 is: 2000

Conclusion

  • Tokens are the smallest elements of a program, and they can be classified into keywords, identifiers, constants, or strings.
  • Keywords in C++ are the collection of reserved words. These are written in lower cases, and we have 95 keywords in C++ available.
  • Identifiers in C++ are short and informative names uniquely identifying variables.
Challenge Time!
quiz
quiz
Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
Free Courses by top Scaler instructors