R. Clayton (rclayton@monmouth.edu)
(no date)
[ A colleague of mine and I were talking about my previous message about
functions without return values, and my colleague expressed the opinion that
a function without an explicit return would return the value of the last
statement in the function body. Although this kind of behavior is familiar
to algol and lisp programmers, it does not match my understanding of how c
works. Nevertheless, my colleague insisted returning the value of the last
statement was the correct behavior, and, a little while later, sent me an
example supporting his claim. Below is my reply to his message. ]
compiles on rockhopper with no warning
executes and returns the last value of k/2
It does, but that's because the g++ compiler uses register 0 to hold the for
index value. When the loop's done, the contents of r0 becomes the return value
for the function.
But the compiler is under no obligation to use r0 to hold a for-loop index
value. The forte compiler use r5 for the index value, and your example works
differently under cc:
$ cat t.c
#include <stdio.h>
int f(int n) {
int k;
for(k=0; k<n/2; k++) ;
}
int main() {
int num;
printf("enter an int: ");
scanf("%d", &num);
printf("f(%d) = %d\n", num, f(num));
}
$ cc t.c
$ ./a.out
enter an int: 10
f(10) = 10
$ ./a.out 12
enter an int: 12
f(12) = 12
$ gcc t.c
$ ./a.out
enter an int: 10
f(10) = 5
$ ./a.out
enter an int: 12
f(12) = 6
$
Under forte compilation, the input parameter is passed in via register 0, and
so becomes the return value in the absence of an explicit return value.
I had to translate your code to c because the CC compiler choked on a non-void
function with no return value. If you look at the assembly generated by CC and
cc, you'll see that the register assignments for the index value are the same.
This archive was generated by hypermail 2.0b3 on Thu Dec 18 2003 - 16:15:05 EST