I thought that the function parameters were pushed onto stack from right to left.

#include <stdio.h>
main()
{
    int i=0;
    printf("%d %d\n",scanf(" %d",&i),i);
    
}

But this code prints out the keyboard entered value instead of 0. Why is it so?

Recommended Answers

All 5 Replies

I thought that the function parameters were pushed onto stack from right to left.

#include <stdio.h>
main()
{
    int i=0;
    printf("%d %d\n",scanf(" %d",&i),i);
    
}

But this code prints out the keyboard entered value instead of 0. Why is it so?

If I enter "42", the output is "1 42". The "1" corresponds to the return value of scanf. What do you expect the output to be?

Cheers,
JD

What compiler are you using? Normally that is correct
The contents of i is pushed
0
Then the output of the scan, 1 character scanned
1
So printout 1 0
If you're seeing the character pushed then your compiler functions differently! It's either parsing left to right, or is optimized such that it resolves the calculations first then pushes just before the call.


STACK:

[ArgB]
[ArgA]
return address
----------

> But this code prints out the keyboard entered value instead of 0. Why is it so?

Given something like printf( "%d %d\n", f(), g() ); the RESULT of g() is indeed pushed first by the standard C calling convention, there is absolutely nothing in the standard that says that g() MUST be called first.

So basically, anything can happen with your combined printf/scanf line.
Neither observed answer is wrong. The code is just broken as it invokes undefined behaviour.

Look up "sequence point" in any good C text.
http://c-faq.com/expr/seqpoints.html

@wildgoose: using code blocks.. what is the output for you?

@yellowSnow- I expected o/p as 1 0. (the other way round)

As I posted { 1, 0 }
From what I remember as the early days of C (spec may have changed since) there was NO specification as to order of the pushes, or how data was processed vs time of push. I always play it safe and make sure I don't do things like that original post. I keep them on separate lines.

It's not really saving you code space and in fact makes the code harder to read the way as posted!

In fact there are several methods of passing argument. One is in fact register passing, not stack passing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.