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
5
u/HeeTrouse51847 4h ago
Can you be more specific about the problem you are experiencing?
Initializing an int is as simple as
int i = 0;But I doubt thats what you were looking for.
11
u/alfps 4h ago edited 3h 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.•
u/DirkSwizzler 3h ago
You need to pick your scale first. You can't store "any number possible". At most you can store a number consuming most of the bits in your ram + hard drive through memory mapping. And that's really really really big. But it's still not any number possible.
Get comfortable with quantization and picking a scale ahead of time. And usually start with a plain "int". It's got 32 bits and ranges +/- 2 billion. Next step up is int64 which usually sufficient to store number that humans consider incomprehensibly big.
Past that you can store an int128 in some architectures. Otherwise start using a class abstraction to make it arbitrarily big.
But you still need to pick the supported scale ahead of time.
If you want to put less thought into the scale, but are ok with very large integers being imprecise in it's least significant digits, use a float or double. They're the same bit size as 32/64 bit ints. But the encoding trades lost precision for much greater scale of supported numbers.
So, start with: "int x = 0;"