简体   繁体   English

让 function1 调用 function2 并让 function2 调用 function1 的干净方法是什么?

[英]What is a clean way to have function1 call function2 and have function2 call function1?

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 .但是,我有两个函数: functionAfunctionB I want functionA to call functionB and functionB to call functionA :我希望functionA调用functionBfunctionB调用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.这里有一种悖论,functionA 需要在 functionB 之前定义,而 functionB 需要在 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.但是,如果我这样做,我不确定如何处理#include语句和头文件。 If the file function2.c has an #include function1.h and function1.c has an #include function2.h it seems kind of circular.如果文件function2.c有一个#include function1.h并且function1.c有一个#include function2.h它看起来有点循环。

Just put include guards in the header and include it in all the .c files you need:只需将包含守卫放在标题中并将其包含在您需要的所有.c文件中:

// 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.稍后您可以在file1.cfile2.c ... file100.c等中执行#include "header.h"并且不会有任何冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM