{} after initialized variable

Write your question here.

new to learning and want to understand what is the {} for after billTotal for? without it "billTotal" in the billTotal = billtotal + billcost line comes up with the error using uninitialized memory, visual studio alt enter help makes this change and code runs fine. just curious why so know when to do and not to do this or if theirs something else to do different better?
thanks :)


string bill;
float billTotal{};
int billNumber;
int billcost;
int numberOfBills;


cout << "how many bills do you have?" << endl;
cin >> numberOfBills;
for (int i = 0; i < numberOfBills; i++)
{
cout << "type in your bill " << (i + 1) << " :";
cin >> bill;
cout << "how much is bill?: " << endl;

cin >> billcost;
billTotal = billTotal + billcost;

cout << "current total is: ";
cout << billTotal << endl;
}
You are looking at ‘initialization syntax’; the {} means to initialize the variable to its default value (using the default constructor, if applicable).

For a float, it is the same as writing:

float billTotal = 0f;

(Since all language-provided numeric values initialize to a value of zero.)


The initialization is required because a simple value (like a float) is not auto-initialized (in local scope — it is initialized to zero in the global scope).

Hence the error you get when you leave off the initializer; the compiler notices that you are adding another value to an uninitialized value, which is meaningless. (Adding 7 to a random number is the same as just starting out with a random number.)


Hope this helps.
The {} syntax also creates a scope. Eg:
1
2
If (1){
}

Any variables declared in the scope cannot be accessed out side the scope.

Hope it helps
@HEAden: Not in this context.


The brace initialization syntax was added to C++ in C++11.
https://akrzemi1.wordpress.com/2011/06/29/brace-brace/
http://www.informit.com/articles/article.aspx?p=1852519

Older material is pre-C++11 and therefore lacks "the new stuff".
Admittedly, one of C’s (and especially C++’s) weaknesses is the confusing contextualization of lexemes. Solve the most vexing parse (a contextual problem with parentheses that confused even compilers) by overloading the meaning of curly braces... Now we are confusing people — and both syntaxes are valid.
Topic archived. No new replies allowed.