C++ (pronounced "C plus plus") is a general-purpose programming language that extends the C programming language with features for object-oriented programming, generic programming, and more. Here is an overview of the C++ syntax:
1. Comments:
- Single-line comments start with //
.
- Multi-line comments are enclosed within /* */
.
// This is a single-line comment
/*
This is a
multi-line comment
*/
2. Preprocessor Directives:
- Preprocessor directives start with #
and are processed before actual compilation.
- Common directives include #include
, #define
, and conditional compilation #ifdef
, #ifndef
, #endif
.
#include <iostream>
#define PI 3.14159
3. Main Function:
- Every C++ program must have a main
function.
- Execution starts from main
.
int main() {
// Your code here
return 0;
}
4. Data Types:
- C++ provides various data types, including int
, float
, double
, char
, bool
, and more.
- You can create user-defined types using classes or structures.
int age = 25;
double price = 12.99;
char grade = 'A';
bool isStudent = true;
5. Variables:
- Declare variables with a data type and an optional name.
- Initialize variables at the time of declaration.
int x;
int y = 10;
6. Operators:
- C++ supports various operators, including arithmetic, comparison, logical, assignment, and more.
int sum = x + y;
bool isEqual = (x == y);
7. Control Structures:
- C++ supports conditional statements (if, else if, else), loops (for, while, do-while), and switch-case.
if (x > 10) {
// Code to execute when x is greater than 10
}
for (int i = 0; i < 5; i++) {
// Loop code
}
8. Functions:
- Functions are defined with a return type, name, and parameters.
- Functions can be called and reused throughout the program.
int add(int a, int b) {
return a + b;
}
9. Classes and Objects:
- C++ supports object-oriented programming with classes and objects.
- Classes encapsulate data and methods.
class Person {
public:
string name;
int age;
void introduce() {
cout << "I am " << name << " and I am " << age << " years old.";
}
};
Person john;
john.name = "John";
john.age = 30;
john.introduce();
10. Pointers and References:
- C++ allows you to work with memory addresses using pointers and references.
int num = 42;
int* ptr = # // Pointer to int
int& ref = num; // Reference to int
11. File I/O:
- C++ provides input and output operations for working with files using ifstream
and ofstream
.
#include <fstream>
ifstream inFile("input.txt");
ofstream outFile("output.txt");
12. Exceptions:
- C++ supports exception handling to manage runtime errors.
try {
// Code that may throw an exception
}
catch (const std::exception& e) {
// Handle the exception
}
This is a high-level overview of C++ syntax. C++ has a rich set of features and libraries that make it suitable for a wide range of applications, from systems programming to game development and more.