-1

My question is about recursion, but is slightly more complicated than than the typical case. Usually, a recursive function calls itself:

int functionName(int x) {
    if (x meets condition) {
        return x;
    }
    else {
        x = functionName(x)
    } 
}

However, I have two functions: functionA and functionB. I want functionA to call functionB and functionB to call functionA:

int functionA(int x) {
    if (x meets condition) {
        return x;
    }
    else {
        x = functionB(x)
    } 
}

int functionB(int x) {
    if (x meets condition) {
        return x;
    }
    else {
        x = functionA(x)
    } 
}

We have a kind of paradox here where functionA needs to be defined before functionB and functionB needs to be defined before functionA.

Presumably, if we have function prototypes appear before the function definitions, we should be okay:

int functionA(int x); // PROTOTYPE
int functionB(int x); // PROTOTYPE

// [insert definition of functionA here]
// [insert definition of functionB here]

However, these inextricably linked processes are rather complicated. If we put both functions inside the same file, we will get what I call the "wall of text effect". The file will be rather long and hard to read. I am tempted to put the two different functions into two different files. However, if I do this, I am not sure what to do about #include statements and header files. If the file function2.c has an #include function1.h and function1.c has an #include function2.h it seems kind of circular.

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • 3
    There is no paradox if you have declared function prototypes. I don't understand your "wall of code" remark, and why you would want to seperate the functions into different files, making the code harder to read. – Weather Vane Oct 22 '17 at 20:07
  • 2
    The else-clause must also return a value. – BLUEPIXY Oct 22 '17 at 20:11
  • There is no paradox, but you might want to reconsider the design and maybe combine the two functions into one, or restructure them so to avoid the circular references. – mnistic Oct 22 '17 at 20:13

1 Answers1

0

Just put include guards in the header and include it in all the .c files you need:

// header.h
#ifndef HEADER_H
#define HEADER_H

int functionA(int x); // PROTOTYPE
int functionB(int x); // PROTOTYPE

#endif

Or simply use this:

#pragma once

int functionA(int x); // PROTOTYPE
int functionB(int x); // PROTOTYPE

Later you can do #include "header.h" in file1.c, file2.c... file100.c etc and there won't be any conflicts.

ForceBru
  • 43,482
  • 10
  • 63
  • 98