0

I'm currently implementing a class for an assignment for my C++ course, but there is one thing I don't fully grasp. As an example I'll use integers, to make this question more general. Let's say we have the following code:

#include <iostream>

int main{     
    int p = { 1 + 2 + 3 };
    int q = 1 + 2 + 3;
    std::cout << p << " - " << q << std::endl;
    return 0;
}

Why is the value for both p and q equal? What is the purpose of the curly brackets? Is there any difference in the way the program is executed or in terms of performance? I'm having a hard time finding the answer to these questions online so thought I'd ask it here.

lrdewaal
  • 101
  • 1
  • 8

1 Answers1

5

For a scalar type, all of these syntaxes:

T p = e;
T p(e);
T p{e};
T p = {e};

mean that p is initialized with the value of e. (These different syntaxes can have different meanings when T is a class type.)

However, with the brace syntax, there is an additional constraint that the conversion must not be narrowing:

int p = 2.5;  // ok
int q = {2.5};  // error

This check is done at compile time, so it should have no effect on performance at run time.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312