2

I am learning C++. I've seen some people doing this:

int a = 2;

But also:

int b(2);

And also:

int c{2};

What am I supposed to use? What are the differences between those?

Thanks, Do'

N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32
DorianV
  • 63
  • 5
  • Related: [https://stackoverflow.com/questions/7612075/how-to-use-c11-uniform-initialization-syntax](https://stackoverflow.com/questions/7612075/how-to-use-c11-uniform-initialization-syntax) – drescherjm Sep 09 '19 at 16:41
  • Also: [https://stackoverflow.com/questions/46403621/why-uniform-initialization-initialization-with-braces-is-recommended](https://stackoverflow.com/questions/46403621/why-uniform-initialization-initialization-with-braces-is-recommended) – drescherjm Sep 09 '19 at 16:42
  • Which book are you using? – Lightness Races in Orbit Sep 09 '19 at 16:43
  • "Uniform initialization syntax" with `{}` is not truly uniform due to `std::initializer_list` complications. Advice to prefer `{}` over `()` is quite outdated now, and in the next C++ standard we're getting a "true" uniform initialization syntax with `()`. However I'm not yet sure how that handles the most vexing parse. – Deji Sep 09 '19 at 16:49
  • related/dupe https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives – NathanOliver Sep 09 '19 at 16:53
  • @NathanOliver the top answer on that question is somewhat outdated as I explained above. It is now dubbed ["*almost* uniform initialization"](https://stackoverflow.com/questions/49952301/c17-almost-uniform-initialization). – Deji Sep 09 '19 at 16:59

1 Answers1

4

What am I supposed to use ?

You can use any of them.

What are the differences between those ?

int a = 2; // A
int b(2);  // B
int c{2};  // C

A is copy initialisation. B and C are direct initialisation.

C uses a braced-init-list and is therefore direct list initialisation. A and B allow initialising with a narrowing conversion while list initialisation allows only non-narrowing conversion. This is sometimes advantageous, since it can help detect unintentional narrowing which is a source of bugs. In this particular case however, it is safe to assume that 2 is appropriate value for int.

eerorika
  • 232,697
  • 12
  • 197
  • 326