-2
int i{0}; //(1)
int i = 0; //(2)

Do I have correct understanding that in first case (1) the variable i will be created already with 0 as it's value, and in (2) it will be created without a value and then assigned a value 0, so (1) will always faster then (2)?

But seems like most(all?) modern compilers will still optimize (2) to be same as (1) under the hood?

Random
  • 249
  • 1
  • 10
  • Is 1 in the question a typo? – 273K Nov 30 '21 at 20:27
  • 3
    No, here they ultimately mean the same thing. Space is allocated for `i` and that space is immediately zeroed. No assignment involved. [See here for documentation](https://en.cppreference.com/w/cpp/language/initialization) – user4581301 Nov 30 '21 at 20:27
  • No, the code will be the same: there's no reason for the compiler to generate slower code with extra assignment. `i` can't be created without value – Dmitry Bychenko Nov 30 '21 at 20:28
  • 1
    [Excellent viewing](https://www.youtube.com/watch?v=7DTlWPgX6zs) if you have an hour and really want to get deep into C++ initialization. – user4581301 Nov 30 '21 at 20:30
  • there is no assigment in your code – 463035818_is_not_an_ai Nov 30 '21 at 20:55
  • @user4581301: Or if you want to know how to look at the asm and answer the question for yourself, Matt Godbolt's CppCon2017 talk [“What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid”](https://youtu.be/bSkpMdDe4g4) shows how. (also [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116)) – Peter Cordes Dec 01 '21 at 00:09
  • @PeterCordes Looks like I upvoted the linked question and answer at some point in the past. May not have watched the video, so I've mailed the link to myself to remind me later. – user4581301 Dec 01 '21 at 00:29

1 Answers1

3

initializing variables with Brace Initialization performs additional checks at compile time (no effect on runtime). . Such as if you enter a float literal inside the curly braces it will throw an error. Initialization with the equal sign will be optimized by the compiler. Prefer brace initialization whenever possible. I hope that answers your question

Kaitou
  • 84
  • 4