C Programming - Expressions - Discussion

Discussion Forum : Expressions - Find Output of Program (Q.No. 12)
12.
What will be the output of the program?
#include<stdio.h>
int main()
{
    int i=2;
    printf("%d, %d\n", ++i, ++i);
    return 0;
}
3, 4
4, 3
4, 4
Output may vary from compiler to compiler
Answer: Option
Explanation:

The order of evaluation of arguments passed to a function call is unspecified.

Anyhow, we consider ++i, ++i are Right-to-Left associativity. The output of the program is 4, 3.

In TurboC, the output will be 4, 3.

In GCC, the output will be 4, 4.

Discussion:
43 comments Page 2 of 5.

Driteknight said:   1 decade ago
GCC or Turbo C compilers are implementations to compile C language. C language hasn't described everything, somethings are implementation dependent. Like the output Neetu has explained is right for GCC but not for Turbo C.

To be precise a compiler works on a CFG (Please refer to it from Wikipedia and leave it if you don't about Finite Automata and Grammar). Dennis Ritchie has explained it in his book "The C Programming Language".

Ranjith karthick said:   10 years ago
How the output for the following produce?

#include<stdio.h>
int main()
{
int a=35;
printf("%d %d %d %d %d ",a++,a++,++a,a++,++a);
return 0;
}

OUTPUT gcc: 39 38 40 36 40.

Shani dubey said:   10 years ago
i++ is postfix increment and ++i is prefix increment. As example:

void main()
{
int i=1;
i=i++;
printf("%d",i);
}

After execute it print output = 2.

In prefix increment:

main()
{
i=1;
i=++i;
}

After execute it print the output = 2.

Manu said:   10 years ago
Please explain this clearly.

Gangadhar said:   1 decade ago
Then why don't you mention whether it is turbo C compiler or GCC compiler?

Pavani,RKValley said:   10 years ago
Post and pre increments evaluated in left to right order.

And displayed left to right order;

Example: i = 2;.

++i, --i.

First we have to calculate --i after that ++i.

Those values are 1, 2.

Displayed values are 2, 1.

Ankit kumar said:   9 years ago
It is mentioned here that in GCC compiler output will be 4 4. How? Explain please.

Kartheek said:   9 years ago
In Linux 4,4 because the priority is from right to left. If pre-increment is there from right to left then the variable is updated.

Ramkumar said:   8 years ago
in turbo C o/p is 4,3.
in c++ o/p is 3,4.
in GCC o/p is 4,4.

Thus the answer will be option D : output will vary from compiler to compiler.

Sathya said:   8 years ago
int j=5,s=5,i=0,m=5,n=5,q=0,h=5;
i=m++ + ++n-j-- - --s;
q=h++ + ++h - h-- - --h;
System.out.println("q:"+q);
System.out.println("i:"+i);
System.out.println("j:"+j);
System.out.println("s:"+s);
System.out.println("j:"+m);
System.out.println("s:"+n);

can you explain this one?


Post your comments here:

Your comments will be displayed after verification.