Value, value, who's got the value?
Geoff Rimmer
geoff at cs.warwick.ac.uk
Sat Apr 29 16:46:27 AEST 1989
In article <1044 at itivax.iti.org> scs at vax3.iti.org (Steve Simmons) writes:
> int func1() { int b ; b = 2 ; }
> int func2() { int c=3 ; c; }
>
> main()
> {
> int a = 1 ;
> printf( "Value of a is %d\n", a ) ;
> a = func1() ;
> printf( "Value of a is %d\n", a ) ;
> a = func2() ;
> printf( "Value of a is %d\n", a ) ;
> }
>
Get a compiler that loves to complain! gcc will do just fine. It'll
print a warning saying that func1 and func2 are *supposed* to return
ints, but that nothing is in fact returned. The idea of this warning
is to stop you thinking that func1() should always return 2 on every
compiler. It may happen, it may not. On our system, the return value
will simply be whatever is left in the d0 register. For example, the
following program:
int func() { int b; b = 2; }
int main() { int a; a = func(); }
produces the following assembler code for func():
_func:
link a6,#-4 ; get 4 bytes for b.
moveq #2,d0 ; set register d0 to 2.
movel d0,a6@(-4) ; move 2 into b.
L1:
unlk a6 ; cleanup heap.
rts ; return to main()
and this for main()
_main:
link a6,#-4 ; get 4 bytes for a.
jbsr _func ; jump to func()
movel d0,a6@(-4) ; move d0 into a. So a becomes 2.
L2:
unlk a6
rts
The compiler writers *could* have implemented this in a totally
different way. They could easily have chosen a different register to
return values from functions, and then, you would get unpredictable
values.
"Glad to be of service!"
Geoff
/---------------------------------------------------------------\
| GEOFF RIMMER - Friend of fax booths, ANSI C, PCBH, |
| phone *numbers* & MPFC & printf |
| email : geoff at uk.ac.warwick.emerald |
| address : Computer Science Dept, Warwick University, |
| Coventry, England. |
| PHONE : +44 203 692320 (10 lines) If I'm out please |
| leave a message with my secretary. |
| FAX : +44 865 726753 |
\---------------------------------------------------------------/
More information about the Comp.lang.c
mailing list