1

I have the following program where the return value is inside a if condition. What would be the return value if the condition is not satisfied?

#include<stdio.h>
int fun(int a)
{
    if(a==5)
            return 100;
}
int main()
{
    int i=5;
    for(;i>0;i--) {
            int j=0;
            j=fun(i);
            printf("func returns %d\n",j);
    }
}

I get the following output

func returns 100
func returns 4
func returns 3
func returns 2
func returns 1

Does this program have UB?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Karthick
  • 1,010
  • 1
  • 8
  • 24
  • 1
    If you are running on an Intel CPU, then the return value will be whatever random value was previously stored within the EAX register (since that is how integer args are returned in most of the calling conventions IIRC). Given that EAX is only set in 'fun' when (a == 5) is true, it depends on what EAX value is set at the callsite (in this case main, and in this case it's using EAX for the i variable). This behaviour will change depending on the OS, the CPU, and where 'fun' is called from. Since it can't be said for certain for it will work, it means you have undefined behaviour. – robthebloke Jul 18 '19 at 07:57

0 Answers0