C++ Variable question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C++ Variable question

What does it mean when there are curly braces right after a variable name? Like this: int a{12} I've also seen something like this: int a{{12}} What are these?

30th Mar 2019, 7:10 PM
Daniel Cooper
Daniel Cooper - avatar
4 Answers
+ 4
There is no difference in this case, they all initialize a with 12. It's just what you prefer. However you should be aware that they cannot be interchanged everywhere. For example std::vector<int> v(10); // Creates a vector with 10 elements std::vector<int> v{10}; // Creates a vector with 1 element int a{}; // a = 0 int a(); // a is a function declaration So yea, learn about the pitfalls of each of them. Personally I prefer the =.
30th Mar 2019, 8:13 PM
Dennis
Dennis - avatar
+ 2
https://www.geeksforgeeks.org/uniform-initialization-in-c/ Also the second example is illegal in this case. std::array<int,10> a{{12}}; is allowed here though.
30th Mar 2019, 7:22 PM
Dennis
Dennis - avatar
+ 2
Exclude the last one. Brain was on auto pilot. Lol
30th Mar 2019, 8:08 PM
Daniel Cooper
Daniel Cooper - avatar
+ 1
interesting So what's the difference between: int a=12 int a(12) int a{12}?
30th Mar 2019, 8:06 PM
Daniel Cooper
Daniel Cooper - avatar