[LCP]what value does the foo() return?

David Spencer david.w.spencer at oracle.com
Mon Jan 5 19:36:02 UTC 2004


The interviewer could have been probing for how much you knew about what 
compilers actually do.  Undefined is the correct answer; however many 
compilers I have met return int values from functions in a CPU register, 
so for those compilers the return value would be whatever is in that 
particular register when the function returns.

If he seemed unsatisfied did you try asking him what he was looking 
for?  "Undefined" is definitely the correct answer to the question you 
have given, and asking for more information in this way wouldn't 
necessarily be seen as bad.  The problem with the answer "Undefined" is 
that it's a one word answer, and interviewers usually want to get to 
know a bit more about you.  Any idiot can read a book and determine the 
answer to the question, so this answer doesn't in itself differentiate 
between an experienced programmer and that idiot.

Whether it's a poor question or not is somewhat beside the point; it may 
suggest the interviewer is an idiot, but then it may suggest the 
interviewer knows a lot more than he is letting on, and in general I 
would have thought it safer to assume the latter, unless of course there 
is additional evidence to suggest the former.  There is a big difference 
between "defined behaviour" and "actual behaviour", and only an 
experienced programmer would be able to answer questions about that 
difference.

As a quick test I tried the following program:

#include <stdio.h>

int foo()
{
  if (0) return 0;
}

int bar()
{
  return 23;
}

int main()
{
  int pq,rs;
  pq=bar();
  rs=foo();
  printf("pq=%d; rs=%d\n",pq,rs);
  return 0;
}

The output from this was "pq=23; rs=23", using MinGW.  I'd guess bar() 
sets some register within my Pentium which is unmodified by the time 
foo() returns, so rs is also set to 23.

Then I duplicated the rs assignment and printf, and this time the output 
was:
pq=23; rs=23
pq=23; rs=13

printf returns (in that same register, presumably) the number of 
characters printed, which for "pq=23; rs=23\n" is 13, hence the 
different value for rs.

Dave.


mehul radheshyam choube wrote:

>>As for the question, using the
>>result of a call to foo() is undefined.  This would be clear
>>from reading any competent book or the Standard.
>>    
>>
>
>    this question was asked to me in an interview. i answered it as undefiened but the the person taking interview was not satisfied. also following is the output i get:
>
>[kalinga at mehul c]$ ./function
>1108545272
>[kalinga at mehul c]$
>
>    any comments on this output?
>
>mehul.
>
>  
>




More information about the linuxCprogramming mailing list