0

the code:

/* find the greatest common divisor of two integers */
#include <stdio.h>
int gcd(int p, int q);

void main()
{
    int u,v,g;
    printf("Enter two numbers: ");
    scanf("%d %d",&u,&v);
    g=gcd(u,v);
    printf("Greatest Common Divisor of %d and %d is %d",u,v,g);
}

int gcd(int a, int b)
{
    int m;
    m=a%b;
    if(m==0)
        return(b);
    else
        gcd(b,m);
}

is working properly on https://www.onlinegdb.com/online_c++_compiler

the code is NOT working on macosx/ sierra with Apple LLVM version 10.0.0 (clang-1000.10.44.4) since the value of the returned variable 'b' does not get assigned to the variable 'g' in line 'g=gcd(u,v);'

'g' always gets the value of 0.

how could this issue be fixed on the mac?

could not find a workaround on stackoverflow.

  • 4
    Maybe it is because you forgot the `return` before the call to `gcb()` in the second last line? – Tenobaal Nov 01 '22 at 18:50
  • 2
    `gcd(b,m);` -> `return gcd(b,m);`. `return` only exits one level of recursion, not all of them. Your compiler should've warned you, compile with `-Wall -Wextra` to enable warnings. (`-std=c++20 -pedantic-errors` is also useful). – HolyBlackCat Nov 01 '22 at 18:50
  • 2
    Also two small things you should change: Please do not use `return(b)`, use just `return b` instead. It is not a function call. And also the main function return `int`, not `void`. You don't have to write `return 0` in the main function since C99 anymore, but you should make the type `int`. – Tenobaal Nov 01 '22 at 18:56

1 Answers1

2

The last line in gcd needs to have a return.

if(m==0)
    return(b);
else
    return gcd(b,m);
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • that's interesting! does this have to do with c standards? 1st) in the onlinegdb platform this last return is not needed, and 2nd) why isn't the else supposed to contain a recursive call only? the recursion is stopped only in the if(m==0) statement and then returning to os? – user9374991 Nov 01 '22 at 19:06
  • That last return *is* needed. It's just luck that it works without the `return`. If you don't return, it's undefined behavior. See https://stackoverflow.com/questions/4644860/function-returns-value-without-return-statement – Andy Lester Nov 01 '22 at 19:27