return value of a function

I have write a shell function to get the maximum of a vector.
However, the returned value from the function is not always
the correct one.

Here is the script:

maxval()
{
local max j i size arrval
size=$1 ; shift
max=-999999999
i=0
while [ $i -lt $size ]
do
 arrval="$1"
 if [ $max -le $arrval ]
 then
  max=$arrval
 fi
 shift
 let i=i+1
done
mvvv=$max
return $max
#mvvv is a global variable
}

#I am accesing mavval via:

maxval `echo ${#ind21[@]} ${ind21[@]}`  

#If I try:

max2=$mvvv  

# transfering via mvvv ; not sure $? does not work.....
# it works

#If I try:

max2=$?

#does not always work.

The question is: Why I am not getting the right answer when I am transfering the output of maxval function via returned $? ?

The return value is effectively truncated into an unsigned short. That is, 0 to 255. The two's complement logic means that -1 gets turned into 255. A return of 256 becomes 0.

Then how can I return a longint (signed or unsigned) from a function via function argument rather then global variable?

For example:
return `echo $var`
still won't work for numbers larger than 255.

you output it to standard out, and "Catch" the output with the `` method you used above:

sub f() { let x=$1; let x=x+255; echo $x }

output=`f 2`

return is designed to return a status, i.e. the function succeeded or failed.

Use echo in the function instead, functions like commands output their results on stdout under Unix.

Edit: Otheus was slightly faster :wink:

Thanks a lot. It worked.