Jump to content

How and when should you use the curly {}" braces in programming specifically in C++ for beginners?


SubhanUllah

Recommended Posts

 

Curly braces are used for initialization of objects. If the object supports it the members (storage) of the object will be directly assigned to the values in the braces.

std::string s{"a string"}; 
 
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 }; 
 
struct X 
{ 
 int x; 
 int y; 
 int z; 
}; 
 
X x{ 1, 3, 5}; 
 
X y =  { 4, 5, 6}; 
This is called Unified Initialization, so that there is a consistent syntax, based around curly braces:

int i{};     // initialized built-in type, equals to int i{0}; 
 
int j{10};  // initialized built-in type 
 
int a[]{1, 2, 3, 4} // Aggregate initialization 
 
X x1{};    // default constructor 
 
X x2{1};   // Parameterized constructor; 
 
X x4{x3}; // copy-constructor 
 
int* arr = new int[5]{ 1, 2, 3, 4, 5 };  //dynamic allocation with initialization 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...