3 Replies - 447 Views - Last Post: 21 August 2011 - 11:23 PM Rate Topic: -----

#1 bijay_ps  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 21-August 11

pre-increment operator

Posted 21 August 2011 - 09:46 PM

Recently I came across a question. I am writing the code here
#include<stdio.h>
void main()
{
  int i,j;
  i=3;
  j=++i*++i*++i;
  printf("%d\n",j);
}

Now when I executed this code I got 216 (as expected). But I got this output in window's Turbo C compiler
only. When I tried executing it on Ubuntu I got 150 :-/ :-/.
And I also tried many chngs in this code,so when I chng it to j=++i*(++i*++i);
I got 216 in ubuntu compiler also. And for j=++i*++i; its giving the correct output,i.e, 25.
So someone please explain me why this is happening? I am using ubuntu 11.04 (Natty narwhal) and gcc compiler.

Is This A Good Question/Topic? 0
  • +

Replies To: pre-increment operator

#2 elgose  Icon User is offline

  • D.I.C Head

Reputation: 102
  • View blog
  • Posts: 228
  • Joined: 03-December 09

Re: pre-increment operator

Posted 21 August 2011 - 10:10 PM

I suggest you do a search in the C++ forum for "operator undefined behavior", you'll see a lot of discussion on your issue.

Basically, this is undefined behavior, so all of your results are "valid" because there is no set, defined way that it should have come out. (link referenced by KYA in another thread)
Was This Post Helpful? 0
  • +
  • -

#3 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: pre-increment operator

Posted 21 August 2011 - 10:44 PM

Run, as quickly as you can, away from such nonsense. It's a subject completely devoid of intelligence, since all code like that, is simply undefined - anything could happen, on any compiler.

One of the surest examples of a waste of time in C, that I know of, BUT:

Welcome to the forum, Bijay_ps! ;)

This post has been edited by Adak: 21 August 2011 - 10:45 PM

Was This Post Helpful? 0
  • +
  • -

#4 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1643
  • View blog
  • Posts: 3,120
  • Joined: 30-May 10

Re: pre-increment operator

Posted 21 August 2011 - 11:23 PM

Similar code, many different compilers
And many different answers.

If anyone is telling you they "know" the answer, ignore them - they simply don't have a clue.

Good programs produce the SAME answer on ALL compilers.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1