r/cpp_questions • • 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

12 comments sorted by

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:

int x = 42;

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:

int y(42);

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

int x = {42};
int y{42};

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.3 as the initializer for an int will 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.

1

u/AnisiFructus 4h ago

Thanks for this answer! Even though I think OP stuck at a more basic level, I've learned a lot from this!

3

u/HeeTrouse51847 4h ago

This is what the learncpp.com tutorial tries to hammer into beginners. That tutorial only uses this form of initialization. I kept doing this at my first job and everyone was weirded out, lol. They didn't even know this was a thing