Curly brackets {}
, also known as braces, are fundamental syntactic elements in C++. They serve multiple purposes in the language, from defining code blocks to initializing variables and containers. Understanding the various uses of curly brackets is crucial for writing correct and readable C++ code.
#include <iostream>
int main() {
int x = 10;
if (x > 5) {
std::cout << "x is greater than 5" << std::endl;
x -= 5;
}
{
int y = 20; // y is only accessible within these braces
std::cout << "y = " << y << std::endl;
}
// std::cout << y << std::endl; // This would cause a compilation error
return 0;
}
if
statement.y
.#include <iostream>
// Function definition
void printMessage() {
std::cout << "Hello from a function!" << std::endl;
}
// Class definition
class MyClass {
public:
MyClass() {
std::cout << "Constructor called" << std::endl;
}
void memberFunction() {
std::cout << "Member function called" << std::endl;
}
};
int main() {
printMessage();
MyClass obj;
obj.memberFunction();
return 0;
}
#include <iostream>
#include <vector>
#include <map>
int main() {
// Array initialization
int arr[] = {1, 2, 3, 4, 5};
// Vector initialization
std::vector<int> vec = {10, 20, 30, 40, 50};
// Map initialization
std::map<std::string, int> map = {
{"one", 1},
{"two", 2},
{"three", 3}
};
// Struct initialization
struct Point {
int x, y;
};
Point p = {10, 20};
// Printing initialized values
std::cout << "Array first element: " << arr[0] << std::endl;
std::cout << "Vector first element: " << vec[0] << std::endl;
std::cout << "Map 'two': " << map["two"] << std::endl;
std::cout << "Point: (" << p.x << ", " << p.y << ")" << std::endl;
return 0;
}
#include <iostream>
#include <vector>
class MyClass {
public:
MyClass(int a, double b) : x(a), y(b) {}
void print() { std::cout << "x: " << x << ", y: " << y << std::endl; }
private:
int x;
double y;
};
int main() {
// Uniform initialization for fundamental types
int i{10};
double d{3.14};
// Uniform initialization for objects
MyClass obj{20, 2.718};
// Uniform initialization for containers
std::vector<int> vec{1, 2, 3, 4, 5};
// Printing values
std::cout << "i: " << i << ", d: " << d << std::endl;
obj.print();
std::cout << "Vector size: " << vec.size() << std::endl;
return 0;
}
{}
can be used as an empty statement or to create an empty initializer list.Understanding and correctly using curly brackets is fundamental to writing clear, correct, and maintainable C++ code. They play a vital role in structuring code, managing scope, and providing flexible initialization options across different versions of the C++ standard.