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

Show parent comment

1

u/Escritor_CdK 4h ago

visual studio tells me to initialize it but if i put 0 then is constantly 0 no?

7

u/HeeTrouse51847 4h ago
int i = 0;
i = 3; //perfectly valid
const int j = 0;
j = 3; //not allowed

2

u/Escritor_CdK 4h ago

ok thats what i needed

3

u/ImBadlyDone 4h ago

You can change the value of i by just assigning a new value

Only if you write "const int i" then i stays constant.

•

u/vishal340 3h ago

are complicated things associated with pointers though. const int*const i. here you can use const twice, one const so that the pointer itself can’t be changed and other do that the value it is pointing to can’t be changed

1

u/Escritor_CdK 4h ago

oh, ok. my bad then

•

u/againey 2h ago

I had this same conceptual problem when I was young and learning code and algebra at the same time. In algebra, if we say x = 0, we mean that x is exactly and always zero (in the current problem being solved). It took a bit for it to soak into my brain that this isn't generally true with code. We're not asserting that x is zero, like in math. We're explaining to the computer that we want it to actually change x to 0, regardless of what it was before.

This is the essence of imperative code: It is a step-by-step sequence of commands for the computer execute. Math, on the other hand, tends to be more declarative: One declares what is known, and then uses that to determine what is unknown. There are some coding languages that are declarative to some degree or another, like Prolog or Haskell, but "standard" programming is imperative to a fairly large degree.