C/C++中相互依赖函数的调用顺序问题求解
Hey Lucas, this is such a common issue when you have functions that need to call each other—don’t worry, it’s easy to fix with function prototypes! Let me walk you through it.
The Problem
C compilers read code top-to-bottom. When your Plus_ou_moins() function tries to call Affichage_menu() at the restart prompt, if Affichage_menu() hasn’t been declared or defined yet, the compiler has no idea what that function is. The same happens if you swap the order: Affichage_menu() calls Plus_ou_moins(), which hasn’t been defined yet.
The Solution: Function Prototypes
A function prototype is a "forward declaration" that tells the compiler: "This function exists, here’s its return type, name, and parameters—you’ll see the full definition later."
All you need to do is add prototypes for both functions before either of their full definitions. Here’s how to adjust your code:
#include <stdio.h> // First, declare prototypes for your mutually calling functions int Plus_ou_moins(); void Affichage_menu(); // Also declare prototypes for your helper functions if they're defined later void Selection_nombre_mystere(); void Choix(); // Global variables (note: using globals works here, but consider passing values as parameters for cleaner code later!) int nombreEntre, nombreMystere, choix; // Now define your game function int Plus_ou_moins() { Selection_nombre_mystere(); printf("\nRentrez un nombre pour commencer\n"); printf("\n"); nombreEntre = -1; // Initialize to avoid unexpected starting values while (nombreEntre != nombreMystere) { scanf("%d", &nombreEntre); if (nombreMystere > nombreEntre) printf("+\n"); else if (nombreMystere < nombreEntre) printf("-\n"); else { printf("Bravo, vous avez trouve le nombre mystere: %d\n", nombreMystere); int restart = 0; printf("Voulez vous jouer de nouveau ? "); scanf("%d", &restart); if (restart == 0) { Affichage_menu(); // Now the compiler knows this function exists! } else { Plus_ou_moins(); } } } return 0; } // Then define your menu function void Affichage_menu(){ printf("=== MENU ===\n"); printf("\n"); printf("1. Plus ou moins\n"); printf("2. Pour combien\n"); printf("3. Options\n"); printf("4. Statistiques\n"); Choix(); switch (choix) { case 1: Plus_ou_moins(); // Compiler recognizes this too, thanks to the prototype break; default: printf("Choix invalide ! Retour au menu.\n"); Affichage_menu(); break; } }
Extra Notes
- Prototypes only need the return type, function name, and parameter types (you can omit parameter names if you want, but including them makes it clearer).
- While global variables work for your small game, consider passing values as function parameters in the future—this makes your code more modular and avoids unexpected side effects from shared variables.
- Your recursive restart logic (calling
Plus_ou_moins()again) is totally fine for a small game like this; you won’t hit stack overflow issues unless someone restarts hundreds of times in a row!
内容的提问来源于stack exchange,提问作者lucas vilella

