+ 4
How to handle the operators ++x and x++ properly and without confusion in variables and operations?
Recently, a strange challenge was presented to me in the section of submissions reviews in the quizz factory. The code was simple at first. There were some variables with their values declared and later an operation which included a mix of operators in form of ++x and x++ and their substraction counterparts. This is where I got stuck. The amount of times I tried to do it right plus the time it took me to answer made me think of how to consider them not to be messed up again.
9 ответов
+ 4
First, if we set the value of a variable as (for example) var e = ++e, it would be the same as I we declared var e += 1, which is shorter. This is not the case for what would be for e++, so be careful.
+ 4
An answer I found was "x++ increments the value of variable x after processing the current statement." But what statement is this? Is it the declaration of the variable or the use of the variable in a function? let's say, as an example:
var x = 10 ;
var y = 12 ;
sumxy = ++x + y++ + x++ + --y ;
+ 3
My apologies, I was thinking more in oop languages
+ 3
The result, however, was 46. In this example, the operation took the values 11 for x twice and 13 and 11 for y. What I expected was that it was 11 and 10 for x and 12 and 11 for y, which results in 44, and just later would add 1 to both x and y.
0
Sorry to say that, but remove the python tag, there is no such operator in that language.
0
I'd say that in your example, you would have: (x+1) + y + x + (y-1) == 2*x + 2*y
0
Hhh
0
There is one more problem..
int x =10, y = 12;
sum=++x + y++ + x++ + --y;
SoloLearnC++ compiler gives sum=46;
But..
Dev-C++ 4.9.9.2 gives sum=45;
So first of all, there is a problem in compiler logic..
Simple example:
int x=10, y=5;
cout<<y++ + 2<<endl;
cout<<x++ + x;
SoloLearnC++ gives 7 and 21;
Dev-C++ 4.9.9.2 gives 7 and 20;
0
Vyacheslav Voskresenskiy In the first example, assuming correct handling of the ++ operations, you would have:
sum = ++x (10+1=11) + y++ (12) + x++ (11) + --y (13-1=12)
So 11+12+11+12= 36...
SoloLearn has the correct output.
For the simple example:
y++(5) +2 = 7 and the new valie for y is 6
x++ (10) + x (10+1=11) = 21
So SoloLearn still has the correct output.
Normally, the ++x expression increments x then uses the new value for x, while x++ uses the old value of x and then increments x.
It seems that Dev-C++ is wrong