13

I came to know and use C++ for 10 years now and I've just seen this syntax:

for(int i{0}; i<5; i++) { }

WTF is this shit??

Comments
  • 7
    Not sure what is the problem, but using

    int i{0} is the same as int i = 0 in c++.

    And using {} is actually a safer way too. Prefer {} initialization over alternatives unless you have a strong reason not to.

    example :

    int x2 = val; // if val == 7.9, x2 becomes 7 (bad)

    int x3 {val}; // error: possible truncation (good)
  • 1
    Yeah, you can also initialize variables with parentheses, which has on several occasions screwed me over when trying to declare methods
  • 2
    @lbfalvy yeah, best practice is to pick one (for most '=') and stick to that one in the project.

    But again, mostly of all devs will use '='.

    Yet it is not the safest option to use in C++ (unless you learned C++ in the 80')

    Here is some info on the convention :

    https://github.com/isocpp/...

    We are now at C++ 23... people should start to move on from the old ones.

    (this was a new feature in C++ 11:

    C++11 provides a syntax that allows for fully uniform type initialization that works on any object)
  • 3
    @Grumm While I know the syntax, I have never seen it being used in a for loop, nor being mentioned as a better way to do things..

    I think it's people just not knowing about it for the most part?

    Thank you for the info~
  • 2
    @Grumm implicit truncating casts are just trouble all around, I'm not sure why c++ still hasn't put them behind a compatibility flag. I think some compilers at least produce a warning.
  • 0
    @Grumm are you Grumm as in the Mojang developer Grumm?
  • 1
    holy shit, since when is this a thing? I haven't written C++ since college.
  • 0
    @ElectroArchiver I agree that in a for loop it is not really needed. But if the code uses that for all the other variables, then yes it makes sense.
  • 2
    @Grumm I didn't suggest that..
  • 1
    @ElectroArchiver My bad. Don't worry, I think most don't use this syntax.

    As long as it works, using '=' is fine and accepted.
Add Comment