944,123 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 566
  • C++ RSS
Dec 3rd, 2007
0

Expression same but different results why

Expand Post »
I am Anwar as a intermediate level currently programming practice in c, c++ and java . In following programs I confused in these expressions that expressions are same but result are different on these results few teachers said it is the problem of compilers.

In Turbo C 3.0
main()
{
int x=-250;
x = --x + --x + --x;
printf("%d",x);
}//it give -259

In Visual C++ 6.0
#include<iostream>
using namespace std;
main()
{
int x=-250;
x = --x + --x + --x;
cout <<x;
}//it give -257

In Java 1.3
class Test
{
public static void main(String abc[])
{
int x=-250;
x = --x + --x + --x;
System.out.print(x);
}//it give -256
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
anwar7517525 is offline Offline
1 posts
since Dec 2007
Dec 3rd, 2007
0

Re: Expression same but different results why

> on these results few teachers said it is the problem of compilers.
No, it's a problem with the teachers not knowing the language rules well enough.

For C and C++, multiple side effects on the same variable has ALWAYS BEEN UNDEFINED.
What does that mean, it means the compiler is free to interpret it however it wants (or maybe even not at all). Any answer you get is just like rolling a dice.
http://c-faq.com/expr/index.html
- my answer is -256
- your answer is -257
- his hard disk has been reformatted.

As for Java, I've no idea whether the Java standard makes any claims about the evaluation order. It's certainly not comparable to C or C++.

The bottom line is that the code is broken. Don't use such constructs in your program, and don't waste time trying to figure out the mysteries of how your compiler seems to work.
Team Colleague
Reputation Points: 5862
Solved Threads: 950
Posting Sage
Salem is offline Offline
7,164 posts
since Dec 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: MP3 Playback in Visual C++
Next Thread in C++ Forum Timeline: IOS ::binary





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC