0
C++ question
Goodmorning, afternoon and evening all. I have a question. I recently finished the C++ course on Sololearn. I am following now an another course to get some more practical experience but this course is making me little bit confused because of what I have learned at the Sololearn course. For example: in Sololearn I have learned to declare a variable like this: int myVarr = 12; In this new course they declare a variable like this: int myVarr {12}; Does this has to do with a newer version of C++? What make me even more confused is that they declare a variable also like this: int myVarr { addTwo(i)}; Do you know how I am supposed to read this?
3 Answers
+ 5
Initializing a variable with {} is called uniform initialization ( C++11 ).
It makes variable initialization more consistent.
Arrays are initialized with {}, so why not variables.
int i = 12 and int i{12} do the same thing.
Additionally it protects you from things like uninitialized variables and from narrowing conversions.
int i; // dunno what i contains
int i{}; // i is default initialized to 0
---
int i = 2.5; // Fine
int i{ 2.5 }; // Error, narrowing conversion
However, just like most things in C++, even these things have a bunch of pitfalls, especially when working with auto, initializer_lists or templates.
Just use whichever you find more convenient.
+ 1
Thank you Dennis and Daniel :) You both have helped me a lot :)