C++ is a powerful, versatile programming language that builds on the foundation of C with additional features for object-oriented, generic, and functional programming. This document outlines the core elements that make up the C++ language.
Structure of a C++ Program
A typical C++ program consists of various sections:
// 1. Include Directives
#include <iostream>
#include <string>
// 2. Namespace Declaration (optional)
using namespace std; // Not always recommended in large programs
// 3. Global Variables/Constants (optional)
const double PI = 3.14159;
// 4. Function Prototypes
void greet(string name);
// 5. Classes/Structures (optional)
class Person {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
void introduce();
};
// 6. Main Function (required)
int main() {
// Local variables
string userName = "John";
// Function calls
greet(userName);
// Object creation
Person person("Alice", 30);
person.introduce();
return 0; // Return statement
}
// 7. Function Definitions
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}
// 8. Method Definitions
void Person::introduce() {
cout << "My name is " << name << " and I am " << age << " years old." << endl;
}
Basic Elements of C++ Language
C++ programs are composed of various elements that work together to create functional software. Here’s an overview of the main elements:
1. Comments
Comments are explanatory text that are ignored by the compiler:
// This is a single-line comment
/* This is a
multi-line comment */
2. Keywords
Keywords are reserved words that have special meaning in C++:
auto break case catch char class
const continue default delete do double
else enum explicit export extern false
float for friend goto if inline
int long mutable namespace new operator
private protected public register return short
signed sizeof static struct switch template
this throw true try typedef typeid
typename union unsigned using virtual void
volatile wchar_t while
3. Identifiers
Identifiers are names given to entities such as variables, functions, classes, etc.
int count; // 'count' is an identifier
void calculateSum(); // 'calculateSum' is an identifier
class Student {}; // 'Student' is an identifier
Rules for identifiers:
- Can contain letters, digits, and underscores
- Must begin with a letter or underscore
- Cannot be a keyword
- Case-sensitive (e.g.,
countandCountare different identifiers)
4. Data Types
C++ provides several built-in data types:
Fundamental Data Types:
| Type | Description | Size (typical) | Range (typical) |
|---|---|---|---|
bool | Boolean | 1 byte | true or false |
char | Character | 1 byte | -128 to 127 |
unsigned char | Unsigned character | 1 byte | 0 to 255 |
int | Integer | 4 bytes | -2,147,483,648 to 2,147,483,647 |
unsigned int | Unsigned integer | 4 bytes | 0 to 4,294,967,295 |
short | Short integer | 2 bytes | -32,768 to 32,767 |
unsigned short | Unsigned short integer | 2 bytes | 0 to 65,535 |
long | Long integer | 4 or 8 bytes | Varies by system |
unsigned long | Unsigned long integer | 4 or 8 bytes | Varies by system |
float | Floating-point | 4 bytes | ±3.4e±38 (approx. 7 digits) |
double | Double precision float | 8 bytes | ±1.7e±308 (approx. 15 digits) |
long double | Extended precision float | 8+ bytes | Varies by system |
void | No value | - | - |
wchar_t | Wide character | 2 or 4 bytes | 1 wide character |
Derived Data Types:
- Arrays
- Functions
- Pointers
- References
User-defined Data Types:
- Classes
- Structures
- Unions
- Enumerations
- Typedefs
5. Variables
Variables are named storage locations that hold values that can be modified during program execution.
int age = 25; // Integer variable
double salary = 50000.50; // Double variable
char grade = 'A'; // Character variable
bool isEmployed = true; // Boolean variable
Variable Declaration and Initialization:
// Declaration without initialization
int count;
// Declaration with initialization
int value = 10;
// Multiple declarations
int x, y, z;
// Multiple declarations with initialization
int a = 5, b = 10, c = 15;
Constants:
Constants are variables whose values cannot be changed after initialization:
// Using const keyword
const double PI = 3.14159;
// Using #define (preprocessor directive, not recommended in modern C++)
#define MAX_VALUE 100
6. Operators
Operators are symbols that tell the compiler to perform specific operations:
Arithmetic Operators:
int a = 10, b = 5;
int sum = a + b; // Addition: 15
int diff = a - b; // Subtraction: 5
int prod = a * b; // Multiplication: 50
int quot = a / b; // Division: 2
int rem = a % b; // Modulus (remainder): 0
Relational Operators:
bool isEqual = (a == b); // Equal to: false
bool isNotEqual = (a != b); // Not equal to: true
bool isGreater = (a > b); // Greater than: true
bool isLess = (a < b); // Less than: false
bool isGreaterEqual = (a >= b); // Greater than or equal to: true
bool isLessEqual = (a <= b); // Less than or equal to: false
Logical Operators:
bool result1 = (a > 0) && (b > 0); // Logical AND: true
bool result2 = (a > 0) || (b < 0); // Logical OR: true
bool result3 = !(a == b); // Logical NOT: true
Assignment Operators:
int x = 10; // Simple assignment
x += 5; // x = x + 5 (x becomes 15)
x -= 3; // x = x - 3 (x becomes 12)
x *= 2; // x = x * 2 (x becomes 24)
x /= 4; // x = x / 4 (x becomes 6)
x %= 4; // x = x % 4 (x becomes 2)
Increment and Decrement Operators:
int a = 5;
int b = ++a; // Pre-increment: a becomes 6, b becomes 6
int c = a++; // Post-increment: c becomes 6, then a becomes 7
int d = --a; // Pre-decrement: a becomes 6, d becomes 6
int e = a--; // Post-decrement: e becomes 6, then a becomes 5
Bitwise Operators:
int a = 5; // Binary: 101
int b = 3; // Binary: 011
int c = a & b; // Bitwise AND: 001 (decimal 1)
int d = a | b; // Bitwise OR: 111 (decimal 7)
int e = a ^ b; // Bitwise XOR: 110 (decimal 6)
int f = ~a; // Bitwise NOT: 11111111111111111111111111111010 (decimal -6)
int g = a << 1; // Left shift: 1010 (decimal 10)
int h = a >> 1; // Right shift: 10 (decimal 2)
Other Operators:
sizeof: Returns the size of a variable or data type? :: Conditional (ternary) operator,: Comma operator.and->: Member access operators::: Scope resolution operatornewanddelete: Dynamic memory allocation/deallocation[]: Array subscript operator(): Function call operator&: Address-of operator*: Pointer dereference operator
7. Expressions and Statements
Expressions:
An expression is a combination of values, variables, operators, and function calls that evaluates to a value.
x + 5 // Arithmetic expression
a > b // Relational expression
a && b || c // Logical expression
Statements:
A statement is a complete line of code that performs some action.
int x = 10; // Declaration statement
x = x + 5; // Assignment statement
if (x > 10) { /* code */ } // Conditional statement
for (int i = 0; i < 10; i++) { /* code */ } // Loop statement
8. Control Structures
Control structures determine the flow of program execution:
Conditional Statements:
// If statement
if (condition) {
// Code executed if condition is true
}
// If-else statement
if (condition) {
// Code executed if condition is true
} else {
// Code executed if condition is false
}
// If-else if-else statement
if (condition1) {
// Code executed if condition1 is true
} else if (condition2) {
// Code executed if condition1 is false and condition2 is true
} else {
// Code executed if both conditions are false
}
// Switch statement
switch (expression) {
case value1:
// Code executed if expression equals value1
break;
case value2:
// Code executed if expression equals value2
break;
default:
// Code executed if no case matches
break;
}
// Conditional (ternary) operator
result = (condition) ? value_if_true : value_if_false;
Loops:
// For loop
for (initialization; condition; increment/decrement) {
// Code to be repeated
}
// While loop
while (condition) {
// Code to be repeated
}
// Do-while loop
do {
// Code to be repeated
} while (condition);
// Range-based for loop (C++11)
for (auto element : collection) {
// Code to process each element
}
Jump Statements:
break; // Exits the enclosing loop or switch statement
continue; // Skips the rest of the current iteration
return x; // Returns a value from a function
goto label; // Jumps to a labeled statement
9. Functions
Functions are blocks of code that perform specific tasks:
// Function declaration (prototype)
return_type function_name(parameter_list);
// Function definition
return_type function_name(parameter_list) {
// Function body
return value; // Optional return statement
}
// Example function
int add(int a, int b) {
return a + b;
}
// Function with default parameters
void greet(std::string name = "Guest") {
std::cout << "Hello, " << name << "!" << std::endl;
}
// Function with reference parameters
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
10. Arrays
Arrays are collections of elements of the same type:
// Array declaration
data_type array_name[size];
// Array initialization
int numbers[5] = {1, 2, 3, 4, 5};
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
// Accessing array elements
int third_element = numbers[2]; // Arrays are zero-indexed
// Multi-dimensional arrays
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
11. Pointers
Pointers are variables that store memory addresses:
// Pointer declaration
data_type* pointer_name;
// Pointer initialization
int x = 10;
int* ptr = &x; // & is the address-of operator
// Dereferencing a pointer
int value = *ptr; // * is the dereference operator
// Null pointer
int* null_ptr = nullptr; // C++11 style
int* null_ptr2 = NULL; // C style (less preferred)
12. References
References are aliases for existing variables:
// Reference declaration and initialization
data_type& reference_name = existing_variable;
// Example
int x = 10;
int& ref = x; // ref is a reference to x
// Modifying through reference
ref = 20; // x is now 20
13. Standard Library Components
C++ provides a rich standard library with various components:
Input/Output Streams:
#include <iostream>
std::cout << "Output to console";
std::cin >> user_input;
String Handling:
#include <string>
std::string greeting = "Hello, World!";
Container Classes:
#include <vector>
#include <list>
#include <map>
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::map<std::string, int> ages = {{"Alice", 30}, {"Bob", 25}};
Algorithms:
#include <algorithm>
std::sort(numbers.begin(), numbers.end());
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
And many more components for mathematics, time, threading, file handling, etc.
Conclusion
Understanding these fundamental elements of the C++ language is essential for writing effective programs. As you become more proficient, you’ll learn to combine these elements in increasingly sophisticated ways to solve complex problems. Remember that C++ is a rich and evolving language, with new features being added in each new standard (C++11, C++14, C++17, C++20, etc.).