Can someone give a detail of this sample coder why the result is 9,and not 4??
-
#include <iostream.h>
int main()
{
int x=1,y;
y= ++x*++x;
cout << x << endl;
cout << y <<endl;
return 0;
}Because you shouldn't use the pre-increment operator that way. :)
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
[My articles] -
#include <iostream.h>
int main()
{
int x=1,y;
y= ++x*++x;
cout << x << endl;
cout << y <<endl;
return 0;
}Hello It's not very hard. answer of this simple question is : YOU WRITE ++x TWICE.y=++x[first time]*++x[second time] don't forget to vote me. BYE...
-
#include <iostream.h>
int main()
{
int x=1,y;
y= ++x*++x;
cout << x << endl;
cout << y <<endl;
return 0;
} -
#include <iostream.h>
int main()
{
int x=1,y;
y= ++x*++x;
cout << x << endl;
cout << y <<endl;
return 0;
}Note that priority of ++ operation is higher than *.If you have
y= ++x*x++
it should be 4. I would recommend you not to use such features because it makes code very hard to understand and modify. Keep it simple and you will avoid getting in troubles. :)Life is a stage and we are all actors!
-
++x // x now = 2
* // will multiply in a moment
++x // x now = 3
// now multiply x(3) by x(3) = 9You should not use expressions like this as they may not give the results you expect.
It's time for a new signature.
Richard MacCutchan wrote:
You should not use expressions like this as they may not give the results you expect.
I welcome you to take a look at our codebase. :laugh:
Workout progress:
Current arm size: 14.4in
Desired arm size: 18in
Next Target: 15.4in by Dec 2010Current training method: HIT
-
Note that priority of ++ operation is higher than *.If you have
y= ++x*x++
it should be 4. I would recommend you not to use such features because it makes code very hard to understand and modify. Keep it simple and you will avoid getting in troubles. :)Life is a stage and we are all actors!
Hristo Bojilov wrote:
Keep it simple
I agree. BTW: the exact order of the expression evaluation and the side-effects has been undefined in many languages for a long time. However IMO a compiler should issue a warning whenever you rely on assumptions, i.e. undefined results. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum
Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.
-
#include <iostream.h>
int main()
{
int x=1,y;
y= ++x*++x;
cout << x << endl;
cout << y <<endl;
return 0;
}This is basically the same question as: http://www.codeproject.com/Messages/3507402/A-Doubt.aspx[^] Where in your class does your colleague sit? I expect you both to get high marks now! Iain.
I am one of "those foreigners coming over here and stealing our jobs". Yay me!