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 3 of 5.

Gaurav said:   1 decade ago
The output varies from compiler to compiler.

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

Deepanshu said:   1 decade ago
@Neethu:

The output in turbo C compiler is :
39 38 38 36 36.

Ganesh marmat said:   1 decade ago
Hi friends.

In gcc compiler the statement use stack code of:

#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.

And only add to it a++ statement.

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

What is output?

Stack contain 36,37,38,39,40,41 when first %d print 40 because a++ post increment if ++a o/p is 41.

2nd %d o/p is 39 if a++ o/p 41.

All post increment represent it stack value and pre increment is higest value.

Anu said:   1 decade ago
printf reads from right to left and if it is assigned value before and we again assigned value and we assigned in printf which value does it take.

Sai charan adurthi said:   1 decade ago
What is the output and how did we get it? Can anyone help me please?

#include<stdio.h>

void main ()
{

int a = 3;
int b = ++a + a++ + --a;
printf ("Value of b is %d", b);

}

Suri said:   1 decade ago
Can anyone please explain in a correct way, bit confusing?

Rahul said:   1 decade ago
Why GCC compiler give the different output?

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.


Post your comments here:

Your comments will be displayed after verification.