Introduction to C++ | Keywords
C++ Keywords
In C++, keywords are reserved words that have a special meaning to the compiler. They are part of the syntax of the C++ language and cannot be used as identifiers (e.g., variable names, function names). C++ has a set of predefined keywords that form the foundation of the language's structure.
Common C++ Keywords
C++ has many keywords, and here are some of the most commonly used:
1. Data Types
- int: Defines an integer variable.
- float: Defines a floating-point variable (single precision).
- double: Defines a floating-point variable (double precision).
- char: Defines a character variable.
- bool: Defines a boolean variable, which can be either true or false.
2. Control Flow
- if: Conditional statement used for decision-making.
- else: Specifies the block of code to execute if the condition is false.
- switch: A control statement for multiple conditions based on a single expression.
- case: Defines a block of code for each value in a switch statement.
- break: Exits a loop or switch statement.
- continue: Skips the current iteration of a loop and proceeds to the next iteration.
3. Functions
- return: Exits a function and optionally returns a value.
- void: Specifies that a function does not return a value.
4. Object-Oriented Programming (OOP)
- class: Defines a class in object-oriented programming.
- private: Specifies private members of a class (not accessible outside the class).
- public: Specifies public members of a class (accessible outside the class).
- protected: Specifies protected members of a class (accessible within the class and derived classes).
- this: Refers to the current instance of the class.
5. Memory Management
- new: Allocates memory dynamically on the heap.
- delete: Deallocates dynamically allocated memory.
Code Example: Using Keywords in C++
Here's an example that demonstrates the use of various C++ keywords.
Code Example
#include <iostream>
using namespace std;
// Function definition
void displayMessage() {
cout << "Hello, this is a simple C++ program!" << endl;
}
int main() {
int num = 10;
bool isActive = true;
// Conditional statement using 'if' and 'else'
if (isActive) {
cout << "The program is active." << endl;
} else {
cout << "The program is inactive." << endl;
}
// Calling the function 'displayMessage'
displayMessage();
// Returning from the function
return 0;
}
Output
The program is active.
Hello, this is a simple C++ program!
Hello, this is a simple C++ program!
Pro Tip:
💡 Pro Tip
When using C++ keywords, remember that they are reserved by the compiler and cannot be used as identifiers for variables or functions. Keywords are fundamental to the syntax and structure of a C++ program, so it is essential to familiarize yourself with them early on to write effective code.