Value, value, who's got the value?
Jeremy Roussak
jeremyr at cs.qmc.ac.uk
Sat Apr 29 08:20:04 AEST 1989
In article <1044 at itivax.iti.org> scs at vax3.iti.org (Steve Simmons) writes:
>
>Consider the following program:
>
>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 ) ;
>}
>
>Compile and run this on a UNIX-PC (system V) under standard cc or
>with gcc, and the result is:
> Value of a is 1
> Value of a is 2
> Value of a is 3
>
>On BSD43. with standard cc or gcc, the result is
> Value of a is 1
> Value of a is 0
> Value of a is 0
>
>Several questions: why does the OS make a difference; why does
>System V get it 'right' (even tho the code is wrong); why do
>none of these flag func2 as having a syntax error?
To answer your questions in reverse order, no syntax error is flagged
because there is no syntax error. A statement in C is simply an expression.
The statement a+3; is perfectly legal: the compiler will add 3 to a and
blissfully throw the result away. Think of the "statement" i++;
It's not so much the OS that makes the difference as the way the compiler
generates code. If it leaves values used in assignments lying around
in a place where they might be interpreted later as results from a function,
and your function carelessly doesn't define a return value, you'll
get a spurious return value. In your case, this is the value you want
but haven't written the code to get. To choose a silly example, some
68000 C compilers use d0 to return function results. If an assignment
a=3
generated code like
move #3,d0
move d0,a (not that it would, one hopes!)
then the value 3 would be lying around in d0 at return time.
Simple, eh?
Jeremy Roussak Just a part-time hacker
More information about the Comp.lang.c
mailing list