C++ Keywords

Welcome to The Coding College! In this tutorial, we’ll dive into C++ keywords—the reserved words in C++ that have predefined meanings and cannot be used as identifiers (like variable names). Understanding keywords is crucial for writing syntactically correct C++ programs.

What Are Keywords in C++?

Keywords are the foundation of the C++ language. Each keyword is reserved by the compiler to perform a specific task, such as declaring variables, controlling program flow, or defining classes and functions.

  • Keywords are case-sensitive.
  • You cannot use them as names for variables, functions, or any other user-defined elements.

Categories of Keywords

C++ keywords can be grouped based on their purpose:

  1. Data Types
  2. Control Statements
  3. Modifiers
  4. Access Specifiers
  5. Error Handling
  6. Others

Let’s explore these categories in detail.

1. Data Type Keywords

These keywords define the type of data a variable can hold.

KeywordPurposeExample
intInteger dataint x = 10;
floatFloating-point datafloat y = 5.5;
doubleDouble-precision floating-pointdouble z = 10.99;
charCharacter datachar c = 'A';
boolBoolean databool flag = true;
voidNo return typevoid display();
wchar_tWide characterwchar_t w = L'A';

2. Control Statements Keywords

These keywords control the flow of a program.

KeywordPurposeExample
ifConditional statementif (x > 0) { ... }
elseAlternative pathelse { ... }
switchMultiple conditionsswitch (x) { ... }
caseA single condition in switchcase 1: ... break;
defaultDefault case in switchdefault: ...
forLoop with a counterfor (int i = 0; ...)
whileLoop with a conditionwhile (x < 10) { ... }
doExecutes before condition checkdo { ... } while();
breakExit a loop or switchbreak;
continueSkip iteration in loopcontinue;
returnExit function and return valuereturn 0;
gotoJump to a labeled statementgoto label;

3. Modifiers Keywords

These keywords modify data types to refine their behavior.

KeywordPurposeExample
signedSigned integersigned int x;
unsignedUnsigned integerunsigned int y;
shortShort integershort int z;
longLong integerlong int a;
constConstant valueconst int b = 10;
volatilePrevent compiler optimizationsvolatile int x;
staticPersistent value in a functionstatic int c;

4. Access Specifiers Keywords

These keywords define access levels in classes and structures.

KeywordPurposeExample
publicMembers accessible to allpublic: int x;
privateMembers accessible within classprivate: int y;
protectedMembers accessible in subclassesprotected: int z;

5. Error Handling Keywords

These keywords handle exceptions in C++ programs.

KeywordPurposeExample
tryBegin exception handling blocktry { ... }
catchHandle an exceptioncatch (...) { ... }
throwThrow an exceptionthrow "error";

6. Other Keywords

These keywords have specialized uses in C++.

KeywordPurposeExample
classDefine a classclass MyClass { ... }
structDefine a structurestruct MyStruct { ... }
enumDefine an enumerationenum Color { Red };
namespaceAvoid name conflictsnamespace MySpace { ... }
usingUse a namespaceusing namespace std;
inlineSuggest inline functioninline void func();
typedefDefine a new type nametypedef int Age;
nullptrNull pointer constantint* ptr = nullptr;
operatorOverload an operatorint operator+(...);

Examples Using Keywords

Example 1: Simple Program

#include <iostream>
using namespace std;

int main() {
    int num = 10;  // Declare a variable
    if (num > 5) { // Use if condition
        cout << "Number is greater than 5" << endl;
    }
    return 0;
}

Example 2: Class Declaration

#include <iostream>
using namespace std;

class MyClass {
    private:
        int x;

    public:
        void setValue(int value) {
            x = value;
        }

        int getValue() {
            return x;
        }
};

int main() {
    MyClass obj;
    obj.setValue(42);
    cout << "Value: " << obj.getValue() << endl;
    return 0;
}

Reserved Identifiers in C++

In addition to keywords, C++ reserves some identifiers for internal use, such as names starting with underscores (_ or __). Avoid using such identifiers to prevent conflicts.

Summary

  • C++ has a rich set of keywords that are essential for programming.
  • Understanding their purpose and usage helps in writing robust and error-free programs.
  • Avoid using keywords as variable or function names.

Explore More at The Coding College

Visit The Coding College for a deeper dive into C++ programming, practical examples, and advanced techniques.

Leave a Comment