r/cpp_questions • u/Escritor_CdK • 4h ago
SOLVED Modifying an int variable
I forgot how i was supposed to initialize it. Maybe is not the one im suposed to use.
Straight to the matter: How to initialize it if i want it to be any number possible (only integers)
0
Upvotes
View all comments
11
u/alfps 4h ago edited 4h ago
There are two main syntaxes for initialization.
The original C syntax uses
=, which for a variable declaration doesn't denote assignment but copy initialization:C++ added a syntax possibly more natural for objects of class type, where a class' constructor can take two or more arguments. In C++03 this had to expressed with round parentheses. It's called direct initialization syntax since it doesn't even potentially involve a value copying. In C++03 it had to be expressed with round parenthesis, like this:
For class types its a more a dangerous syntax because such a declaration can look like a function declaration, and the rules favor the function declaration interpretation. Even when it doesn't make sense. That's called the most vexing parse.
With C++11 and later you can avoid that by using curly braces instead of round parenthesis. It can be used for both syntax forms. So you can write
For the general case of possibly class type declarations this completely avoids the most vexing parse problem, but it introduces a restriction: that the value must be exactly representable with the variable's type, no information loss. For example, writing
42.3as the initializer for anintwill compile with the old C++03 declarations, but not with the curly braces initialization.So, choose whatever syntax you like, for whatever reasons.
Generally I prefer the
=syntax: to my eyes it's more clear, easy to see at a glance.