Home > front end >  Why does this function returns size of array when there is no return statement?
Why does this function returns size of array when there is no return statement?

Time:04-11

I'm getting output as 8 for this program. Why is this function returning size of array when there is no return statement? It is working properly when I write the return statement but I'm still curious why this function is returning the size of array. I thought it should return garbage value.

#include <stdio.h>
int sumofelements(int A[],int size)
{
    int i,sum=0;
    for(i=0;i<size;i  ) 
        sum = sum   A[i];
}

int main()
{
    int A[]={3,4,5,6,3,6,1,10};
    int size=sizeof(A)/sizeof(A[0]);
    int total=sumofelements(A,size);
    printf("sum of the elements=%d",total);
}

CodePudding user response:

Not explicitly returning a value from a non-void function (except main()) results in Undefined behavior. This means that anything can happen: a crash, returning garbage value, or worse of all, the expected value!

You should always return something (meaningful) from a non-void function.

CodePudding user response:

Return values are picked from eax which is a register on your CPU (registers are like your CPU’s own place to store some small amounts of data outside of RAM) it happened to be that eax contained the size of the array just before your function ended.

Probably in i < size, size is stored in eax and is not modified any further until your function ends, but you would have to objdump -d your program and paste it here for me to say anything certain.

If you want to learn more type “CPU registers” and read some stuff online.

So, just put a return value… :)

CodePudding user response:

The behavior is undefined. Any value is possible, including the observed behavior. And on some exotic architectures, a trap value might cause other strange behavior.

For your particular case, the place where sumofelements is expected by main to have placed its return value (some CPU register) happens to contain the value of size, but no guarantee whatsoever: it might not on a different combination of CPU/OS/compiler/set of options/time of day...

Use gcc -Wall -Werror or a similar warning level to avoid such silly mistakes.

You can look at the assembly and behavior on Godbolt's Compiler Explorer and play with compiler flags and compiler versions to see how volatile the behavior is. With -O2, both gcc and clang generate a simple ret instruction for sumofelements and do not even call this function for the printf call.

  • Related