Keywords in C++ : Different Types with Examples

Updated on August 12, 2024

Article Outline

When you first start learning C++, the huge number of keywords may overwhelm you. Everybody has been there. Writing quality code requires familiarity with this large number of keywords in C++.

 

These keywords have special meanings, and using them correctly is key to mastering the language.

 

There are a total of 95 keywords that form the backbone of C++ programming. From managing control flow to defining data types and handling memory, keywords make C++ versatile and robust.

 

For a beginner, the number of keywords might seem overwhelming. But each keyword plays a vital role and understanding them will unlock the full potential of C++.

 

In this blog, we shall examine these keywords, their significance, and their use.

Tokens in C++ and Their Classification

In C++, the smallest building blocks of a program are tokens. Think of tokens as the basic ingredients in a recipe.

 

Types of Tokens:

Types of Tokens in C++

Each token type has a role in making your C++ program run smoothly.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Overview of All 95 C++ Keywords

C++ has 95 keywords. Each one has a specific function in the language.

 

Here’s the full list:

 

alignas alignof and and_eq asm
atomic_cancel atomic_commit atomic_noexcept auto bitand
bitor bool break case catch
char char8_t char16_t char32_t class
compl concept const consteval constexpr
constinit const_cast continue co_await co_return
co_yield decltype default delete do
double dynamic_cast else enum explicit
export extern false float for
friend goto if inline int
long mutable namespace new noexcept
not not_eq nullptr operator or
or_eq private protected public reflexpr
register reinterpret_cast requires return short
signed sizeof static static_assert static_cast
struct switch synchronized template this
thread_local throw true try typedef
typeid typename union unsigned using
virtual void volatile wchar_t while

 

Detailed Explanation of Common C++ Keywords

Understanding the most common C++ keywords helps in writing effective code.

 

1. auto

 

The auto keyword lets the compiler deduce the type of a variable from its initializer.

 

2. bool

 

The bool keyword defines a boolean variable that can be true or false.

 

3. break

 

The break keyword exits a loop or switch statement immediately.

 

4. case

 

The case keyword defines a branch in a switch statement.

 

5. catch

 

The catch keyword handles exceptions thrown by try.

 

6. char

 

The char keyword defines a character variable.

 

7. class

 

The class keyword defines a user-defined type with data and functions.

 

8. const

 

The const keyword defines variables whose values cannot change.

 

9. continue

 

The continue keyword skips the current iteration of a loop and moves to the next.

 

10. default

 

The default keyword specifies the default block of code in a switch statement.

 

11. delete

 

The delete keyword deallocates memory that was previously allocated with new.

 

12. double

 

The double keyword refers to double-precision floating-point variables.

 

13. else

 

The else keyword is used in combination with if to provide a different block of code to run if the condition is false.

 

14. enum

 

The enum keyword specifies an enumeration, which is a user-defined data type made up of named integer constants.

 

15. explicit

 

The explicit keyword disables implicit conversions and copy-initialization of constructors and conversion operators.

 

16. float

 

The float keyword defines single-precision floating-point variables.

 

17. for

 

The for keyword initiates a loop that iterates over a range of values.

 

18. friend

 

The friend keyword allows a function or another class to access private or protected members of a class.

 

19. int

 

The int keyword defines integer variables.

 

20. long

 

The long keyword defines long integer variables.

 

21. mutable

 

The mutable keyword allows a member of a const object to be modified.

 

22. new

 

The new keyword allocates memory dynamically.

 

23. operator

 

The operator keyword is used to overload operators.

 

24. private

 

The private keyword indicates that class members are only available within the class.

 

25. protected

 

The protected keyword indicates that class members are available inside the same and derived classes.

 

26. public

 

The public keyword indicates that class members are available from outside the class.

 

27. register

 

The register keyword indicates that the compiler saves the variable in a register.

 

28. return

 

The return keyword retrieves a value from a function.

 

29. short

 

The short keyword refers to short integer variables.

 

30. sizeof

 

The sizeof keyword calculates the size of a data type or object in bytes.

 

31. static

 

The static keyword refers to static members or variables that preserve their value between function calls.

 

32. struct

 

The struct keyword defines a structure, a user-defined data type that groups related variables.

 

33. switch

 

The switch keyword implements a multi-way branch statement.

 

34. this

 

The ‘this’ keyword refers to the current instance of a class.

 

35. throw

 

The throw keyword throws an exception.

 

36. true

 

The true keyword represents the boolean value true.

 

37. try

 

The try keyword begins a block of code that will be tested for exceptions.

 

38. typedef

 

A data type’s alias is created using the typedef keyword.

 

39. union

 

The union keyword specifies a union as a user-defined data type that can only carry one non-static data member at a time.

 

40. virtual

 

For polymorphism, virtual functions are defined with the virtual keyword.

 

41. void

 

The void keyword specifies that a function does not return a value.

 

42. volatile

 

The volatile keyword indicates that the value of a variable can change at any point without requiring any action from the code.

 

43. while

 

The while keyword starts a loop that lasts as long as a condition is true.

Keywords Unique to C++ and Their Significance

Ever wondered what makes C++ unique? It’s the special keywords not found in C. These keywords give C++ its powerful features.

 

Here are the unique 30 Keywords in C++ Language which are not available in C language:

 

asm dynamic_cast namespace reinterpret_cast bool
explicit new static_cast false catch
operator template friend private class
this inline public throw const_cast
delete mutable protected true try
typeid typename using virtual wchar_t

 

Let’s dive into a few examples.

 

1. class

 

The class keyword allows us to create our own data types.

 

2. virtual

 

The virtual keyword supports dynamic polymorphism.

 

3. namespace

 

The namespace keyword helps organize code.

 

4. explicit

 

The explicit keyword prevents unwanted implicit conversions.

 

5. constexpr

 

The constexpr keyword is used to compile time constants.

 

6. nullptr

 

The nullptr keyword represents a null pointer.

Type Qualifiers in C++ and Their Usage

Type qualifiers add extra meaning to variables. They help control how variables are used and accessed.

 

Here are the main type qualifiers:

type qualifiers in C++

1. const

A const variable’s value cannot be changed after initialisation.

 

Example:

 

#include<iostream> using namespace std; int main() {     const int maxScore = 100;     cout << "Max Score: " << maxScore << endl;     // maxScore = 110; // Error: cannot modify a const variable     return 0; }

Output:

Max Score: 100

2. volatile

A volatile variable can be changed at any time, bypassing normal code.

 

Example:

#include<iostream> using namespace std; volatile int timer = 0; int main() { timer = 10; cout << "Timer: " << timer << endl; return 0; }

Output:

Timer: 10

3. mutable

A mutable member of a const object can be modified.

Example:

#include<iostream> using namespace std; class Data { public: mutable int counter; Data() : counter(0) {} }; int main() { const Data d; d.counter = 10; cout << "Counter: " << d.counter << endl; return 0; }

Output:

Counter: 10

4. restrict

A restrict pointer is the only pointer to an object.

 

Example:

#include<iostream> using namespace std; void updateValue(int* restrict ptr, int value) { *ptr = value; } int main() { int x = 5; updateValue(&x, 10); cout << "Updated Value: " << x << endl; return 0; }

Output:

Updated Value: 10

Differences Between Keywords and Identifiers in C++

Keywords and identifiers are essential in C++ but serve different purposes.

 

Keywords:

 

  • Reserved words.
  • Have predefined meanings.
  • Cannot be used as identifiers.

 

Identifiers:

 

  • Names for variables, functions, etc.
  • Defined by the programmer.
  • Must follow naming rules.

 

Comparison Table:

 

Aspect Keywords Identifiers
Definition Predefined reserved words User-defined names
Case Sensitivity Always in lowercase Can start with uppercase or lowercase
Purpose Defines the type of entity Classifies the name of the entity
Character Composition Only alphabetical characters alphabets, digits, and underscores
Special Symbols No special symbols or punctuations Only underscores are allowed
Examples int, char, while, do Hero_Vired, HV, Hv1
Reserved for Syntax Reserved for specific syntax and functionality Created by coders for their program
Usage To declare data types, control structures, etc. For naming variables, functions, etc.

 

Reserved Identifiers and Special Identifiers in C++

Have you ever been surprised by identifiers that begin with an underscore? You’re not alone. Reserved and special identifiers can trip up even seasoned programmers.

 

In C++, some identifiers are reserved. They include:

 

  • Identifiers with double underscores (__).
  • Identifiers starting with an underscore followed by an uppercase letter.
  • Identifiers starting with an underscore in the global namespace.

 

Examples:

 

  • __func__: Used to access the name of the current function.
  • _MyVariable: Reserved if used at the global scope.

Some identifiers have special meanings.

 

Examples:

 

  • final: Used in class declarations to prevent inheritance.
  • override: Ensures a method overrides a base class method.

 

These identifiers ensure consistent and error-free code.

Examples of C++ Keywords in Action

Example 1: Using auto for Type Inference

#include<iostream> using namespace std; int main() { auto x = 10; auto y = 3.14; cout << "x: " << x << ", y: " << y << endl; return 0; }

Output:

x: 10, y: 3.14

Example 2: Exception Handling with try and catch

#include<iostream> using namespace std; int main() { try { throw runtime_error("An error occurred"); } catch (const runtime_error& e) { cout << "Caught: " << e.what() << endl; } return 0; }

Output:

Caught: An error occurred

Example 3: Memory Management with new and delete

#include <iostream> using namespace std;  int main() { int* numbers = new int[5]; for (int i = 0; i < 5; ++i) { numbers[i] = i * 2; } for (int i = 0; i < 5; ++i) { cout << numbers[i] << " "; } delete[] numbers; return 0; }

Output:

0 2 4 6 8

Example 4: Using constexpr for Compile-Time Constants

#include<iostream> using namespace std; constexpr int square(int x) { return x * x; } int main() { int result = square(5); cout << "Square: " << result << endl; return 0; }

Output:

Square: 25

Example 5: Implementing Polymorphism with virtual

#include <iostream> using namespace std;  class Animal { public: virtual void sound() { cout << "Animal sound"; } };  class Dog : public Animal { public: void sound() override { cout << "Bark"; } }; int main() { Animal* a = new Dog(); a->sound(); delete a; return 0; }

Output:

Bark

Conclusion

In this blog, we explored the core and unique keywords in C++. We looked at examples of keywords such as auto, try, catch, new, and virtual.

 

These examples demonstrated how these keywords function. Understanding these can help you write cleaner and more effective code.

 

We also distinguished between keywords and identifiers, ensuring clarity in naming conventions.

 

By mastering these keywords, we can write cleaner, more efficient C++ code. Keep practicing these concepts to strengthen your programming skills and make your C++ journey more rewarding.

FAQs
Keywords in C++ are reserved words with special meanings. They are crucial for the syntax and structure of C++ programs.
Unfortunately, keywords cannot be used for the variable name since they are reserved by the language.
There are 95 keywords in C++.
Keywords have system-provided meanings, while identifiers are the names defined by the user for variables, functions, and other entities.
No, some keywords are unique to C++ and are not available in the C programming language, such as class, virtual, namespace, and explicit.
No, there are some keywords exclusive to C++, such as class, virtual, namespace, and explicit, which do not exist in this C language.

Updated on August 12, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved