Explain this code behaviour

Please read the comment.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int M(int i)
{
	printf("%d\n",i++);	
}

int main ()
{
int i=10;
printf("%d\n",M(i));  
/*
I think calling M here should  print 10 and a garbage return value from the function call, as it is not returing anything.
but the output is 10 and 3 ? Can you explain this ? 
*/
return 0;
}
Yes. Garbage value happened to be 3 here.
Explain this code behaviour


Well firstly it doesn't compile for me. You've told the compiler function M() returns an int, but you don't return an int.

If you return 'i' from your function you get sensible results i.e.

10
11


what compiler are you using?
Last edited on
Both GCC and Clang compiles just fine. It is not technically an error in all cases.

What error message do you get?
@MiiNiPaa: I tried changing the value of i to 100 and 1000, it gives out garbage value as 4 and 5 respectively? looks like garbage value is of some significance here? I guess it's returing number of digits+1 in the number I'm inputting. O.o

@mutexe: I'm using Dev-C++ 5.7.0, it complies fine here.
Last edited on
You see, on PC stack is usually used to pass and return parameters and store local variables. Often when you do something like your code, you sometimes encounter leftovers from previous operation or data written later.

In your case you are probably reading printf() return value, which is amount of characters written (digits + newline). WIth optimisations turned on I get 0. Coliru crashes.
http://coliru.stacked-crooked.com/a/f309890ea8668f65

So if you had an idea that this behavior is predictable, forget it.
@MiiniPaa: Thanks for the explaination. :)

Anyhow, This was a question asked in Oracle recruitment exam.
Last edited on
Error	1	error C4716: 'M' : must return a value	


Visual Studio Premium 2013...
Ah, VS threats some level 1 warnings as errors by default.
which i like.
SAdly there are little of them. And it does terrible job of determine if there is need to did that diagnostic and some diagnostics are to high in level in my opinion.

Well, nothing which cannot be fixed by fine-tuning compiler settings which you should do anyway.
Topic archived. No new replies allowed.