I'm a beginner at C++ and I have a question.
include <iostream>
using namespace std;
void main()
{
int myage = 25;
cout << "I am" << myage++ << "years old." << endl;
cout << "You are" << ++myage << "years old." <<
endl;
cout << "She is" << --myage << "years old." << endl;
cout << "I am" << myage-- << "years old." << endl;
}
If you write the code like this
I am 25 years old.
You are 26 years old.
She is 24 years old.
I am 25 years old.
I think the result should come out like this
I am 25 years old.
You are 27 years old.
She is 26 years old.
I am 26 years old.
If you look at the output, it comes out as above, what's the reason?
c++
In C language, ++
or --
is an increase or decrease operator, which increases or decreases the number by 1.
If the increment/decrease operator precedes a variable, it increments or decrements the variable by 1, and if it precedes the variable, it passes the current value first, then increases or decrements by 1.
myage = 25
myage++ // print out the current value of 25 and save 26 plus 1
++myage // output 27 plus 1 from the current value and store 27
--myage // Output 26 minus 1 from the current value of 27 and store 26
myage-- // print out the current value of 26 and save 25 minus 1
Therefore, it is correct to follow the results below.
© 2024 OneMinuteCode. All rights reserved.