Explanation
Sep 12, 2019 at 3:42am UTC
Why does the first line of code function properly while the second line causes errors?
int num_twenties{total_pennies / TWENTIES};
1 2 3 4
int num_twenties;
{
total_pennies / TWENTIES;
}
If I remove the semicolon after the variable on the second code it won't run, but if I change the format to such as the first code, alls good?!
Sep 12, 2019 at 4:09am UTC
Sep 12, 2019 at 4:13am UTC
Your ; is inside the brace, and not outside.
In the right place, it doesn't matter how you format it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
$ cat foo.cpp
#include <iostream>
const int TWENTIES = 20;
void foo ( int total_pennies ) {
int num_twenties{total_pennies / TWENTIES};
std::cout << "T=" << num_twenties << std::endl;
}
void bar ( int total_pennies ) {
int num_twenties
{
total_pennies / TWENTIES
};
std::cout << "T=" << num_twenties << std::endl;
}
$ g++ -c -std=c++11 foo.cpp
Sep 12, 2019 at 4:24am UTC
The first version, what I wrote in another topic of yours, is called "uniform initialization."
A different way to write
int num_twenties = total_pennies / TWENTIES;
https://www.learncpp.com/cpp-tutorial/variable-assignment-and-initialization/
What you did is create variables without assigning any value to them. The code block in the braces doesn't do anything because it doesn't assign the expected value to the newly created variable.
You already asked this question in another topic, which I answered, no need to create a new topic.
Sep 12, 2019 at 4:27am UTC
Sep 13, 2019 at 8:58pm UTC
Apologies for the multiple posts. Thank you all for the responses.
Topic archived. No new replies allowed.