Syntax Error/Possibly Logical in a Recursive Function

Asked

Viewed 46 times

1

Statement of the question: Consider the following functions:

int suc(int n) { return n+1; }
int pred(int n) { return n-1; }

Using these functions (and no arithmetic operator), create recursive functions to determine: (a) The sum of two natural numbers.

#include <stdio.h>

#define pred(n) { return n-1; } 
#define suc(n) { return n+1; } 

int soma (int x, int y ){
if ( x == 0) return y;
if ( y == 0) return x;
return soma((suc(x)),(pred(y)));
}

int main(void){
int x = 4;
int y = 3;
int result = soma(x,y);
}

Can anyone tell me what is the syntax/logic error in this solution? Thank you from now on

  • 3

    It wouldn’t just be #define pred(n) n-1? As I recall, this is a macro, not a function.

  • Thank you very much! That’s right, I just corrected and it worked!

  • Macros are questionable. In this answer i Linko several references criticizing the use of them. In short, make conscious use of this functionality. Possibly you do not need it

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.