Explanation

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?!
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
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.
rjphares and salem c,

The OP was confused by examples of uniform initialization in another topic.

http://www.cplusplus.com/forum/beginner/262229/#msg1133606

It is NOT a namespace, neither is it a malformed function.
Apologies for the multiple posts. Thank you all for the responses.
Topic archived. No new replies allowed.