Make functions call each other - C - c

A noob question: I created a library called funcoes.h that have a menu() and other functions that can call menu(). An example:
void cifrar(){
printf("\n\nDeseja cifrar outra mensagem? Digite 1 para Sim ou 2 para sair: ");
scanf("%d", &exit);
if(exit == 1){
cifrar();
}
else{
menu();
}
}
void menu(){
printf("Escolha uma das opcoes: ");
scanf("%d", &varMenu);
switch(varMenu){
case 1:
system("cls");
cifrar();
break;
case 2:
system("cls");
decifrar();
break;
case 3:
system("cls");
sair();
break;
default:
system("cls");
printf("Escolha uma opcao valida!\n\n");
menu();
break;
}
}
But when I compile, I have this error:
In function 'void cifrar()'
'menu' undeclared(first use this function)"
'void menu()' used prior to declaration
How to make them call each other without this error?
Thanks!

every function that you call has to be declared BEFORE that call. you can do this by using a prototype of that function:
void menu();
void cifrar() {
...
}
void menu() {
..
}
or simply by putting the whole main function (with it's body) on top of cifrar.

Well, maybe it would be nice to sum up what is in comments.
The compiler wants to know any function's prototype before this function is used somewhere else. 'Before' here means something like 'earlier in the source file'. You can, although, place all the prototypes in a separate .h file, include it in the .c file with actual code, and then place function implementations in whatever order you like - the compiler will not complain.

What you should do, is to create a header file, which will have the signatures of all your functions and then you do not need to worry about where each function is located at the code, you will be able to use all of the functions all over the code.
Your code should look like this:
funcoes.h
void cifrar(void);
void menu(void);
funcoes.c
#include "funcoes.h"
void cifrar(void){
printf("\n\nDeseja cifrar outra mensagem? Digite 1 para Sim ou 2 para sair: ");
scanf("%d", &exit);
if(exit == 1){
cifrar();
}
else{
menu();
}
}
void menu(void){
printf("Escolha uma das opcoes: ");
scanf("%d", &varMenu);
switch(varMenu){
case 1:
system("cls");
cifrar();
break;
case 2:
system("cls");
decifrar();
break;
case 3:
system("cls");
sair();
break;
default:
system("cls");
printf("Escolha uma opcao valida!\n\n");
menu();
break;
}
}
Another small tip, do not create functions without any arguments, such as:
void menu();
Always insert the arguments you want to pass. If you want the functions to get not arguments, just pass void.
void menu (void);

Related

Fixing C switch statement function overflow?

int main (void)
{
*/ function prototypes */
print_case();
do_something1();
do_something2();
do_something3();
do_something4();
exit_program();
program_invalid();
}
void print_case (void)
{
int i;
printf("\n"
"1. Do Something 1\n"
"2. Do Something 2\n"
"3. Do Something 3\n"
"4. Do Something 4\n"
"5. Exit the program\n"
"Enter choice (number between 1-5)>\n");
scanf("%d", &i);
switch(i)
{
case 1:
do_something1();
break;
case 2:
do_something2();
break;
case 3:
do_something3();
break;
case 4:
do_something4();
break;
case 5:
exit_program();
break;
default:
program_invalid();
break;
}
return;
}
something_t do_something1(void)
{
something_t something;
printf("Something 1\n");
return something;
}
void do_something2(something_t something)
{
printf("Something 2\n");
}
void do_something3()
{
printf("Something 3\n");
}
void do_something4()
{
printf("Something 4\n");
}
void exit_program (void)
{
exit(0);
}
void program_invalid (void)
{
printf("Not valid choice");
}
So basically when I compile it and execute the code and select the various cases, it will execute multiple functions at once and prints out multiple statements at once. Let's say I choose case 1 the output it prints Something 1 but when I choose case 2 it prints
Something 1
Something 2
and when I choose case 3 it prints
Something 1
Something 2
Something 3
So how would I fix my code to get out of the loop? I thought break statements would only let it execute one function at a time. Yes the something_t references to my typedef structures that I didn't include in my code.
print_case() has the switch. It does its thing then returns. What you THINK are function prototypes in main() are actually just calls. So it calls them. And so you see all of the functions executing. C has a habit of shrugging and making that work, because traditionally it is very tolerant. Move your 'prototypes' out to before main() and preferably put a proper signature on them all.
Your do_something2 has an arg, but you are not declaring it in the (non-working) fake prototype - that is, it will be incorrect once you move it out to before main().
Also, since you have declared do_something2() to take an arg, you'd better pass one!
why are you putting something_t as input into your function. The code your posting also will not compile.
you also have a gap in the name and are missing a function type for function something_t do_something1(void).
Here is the clean version of your code , I think this might help you remember some stuff.
#include <stdio.h>
#include <stdlib.h> // for exit.
#define True 1 // Symbolic constants.
/*
* This is a multi-line comment.
* -----------------------------
* These is how a function prototype
* should be.
* You can leave the parameter names
* empty because in function prototypes
* the parameter names are dumy but not
* the types.
*/
typedef int something_t; // You can have any structure here.
// just for an example.
void print_case(void);
something_t do_something1(void);
void do_something2(something_t);
void do_something3(void);
void do_something4(void);
void exit_program (void);
void program_invalid (void);
// ---- This is a single line comment.
int main()
{
while(True) {
print_case();
}
return 0;
}
void print_case (void)
{
int i;
printf("\n"
"1. Do Something 1\n"
"2. Do Something 2\n"
"3. Do Something 3\n"
"4. Do Something 4\n"
"5. Exit the program\n"
"Enter choice (number between 1-5)>\n");
scanf("%d", &i);
switch(i) {
case 1:
do_something1();
break;
case 2:
do_something2(True); // must pass your struct.
break;
case 3:
do_something3();
break;
case 4:
do_something4();
break;
case 5:
exit_program();
break;
default:
program_invalid();
break;
}
return;
}
something_t do_something1(void)
{
something_t something;
printf("Something 1\n");
return something;
}
void do_something2(something_t something)
{
printf("Something 2\n");
}
void do_something3(void)
{
printf("Something 3\n");
}
void do_something4(void)
{
printf("Something 4\n");
}
void exit_program (void)
{
exit(0);
}
void program_invalid (void)
{
printf("Not valid choice");
}

Undefined reference to pesquisar_bin

//Ordenacao por insercao/selecao
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
int vet[10]={8,16,34,13,19,7,45,3,12,9},a,b,aux;
void selecao();
int pesquisar_bin(int,int,int,int);
int main (){
int opt=0,num,max;
char continuar;
printf("ESCOLHA O METODO DE ORDENACAO:\n\
1- INSERCAO\n\
2- SELECAO\n\
3- SAIR\n");
do{
scanf("%d",&opt);
}while(opt!=1 && opt!=2 && opt!=3);
switch(opt){
case 1:
break;
case 2:
selecao();
break;
case 3:
exit(1);
break;
}
printf("\n\n1- PESQUISA SEQUENCIAL\n\n\
2- PESQUISA BINARIA\n");
do{
aux=0;
scanf("%d",&aux);
}while(aux!=1&&aux!=2);
printf("DIGITE O VALOR A SER PESQUISADO:\n");
scanf("%d",&num);
else if(aux==2){
max=sizeof(vet)/sizeof(int);
pesquisar_bin(vet[max],0,max,num);
}
}
//ORDENACAO POR SELECAO
void selecao(){
int i=1;
do{
b=0;
for (a=0;a<9;a++){
if(vet[a+1]<vet[a]){
aux=vet[a];
vet[a]=vet[a+1];
vet[a+1]=aux;
b=1;
}
}
if(b==1){
printf("Fase %d: [",i);
for(a=0;a<10;a++){
printf("%d ",vet[a]);
}
printf("]\n\n");
i++;
}
}while(b==1);
}
//PESQUISA BINARIA
int pesquisar_bin(int vetor[],int ini,int fim,int numero){
int pos;
pos=((fim-ini)/2)+ini;
if (ini>fim){
printf("Valor %d nao encontrado no vetor\n",numero);
return 0;
}
if(numero>vet[pos]){
return (pesquisar_bin(vet,pos+1,fim,numero));
}
else if(numero<vet[pos]){
return (pesquisar_bin(vet,ini,pos-1,numero));
}
else if(numero==vet[pos]){
printf("O valor %d se encontra na posicao %d do vetor.",numero,pos);
return 0;
}
}
I've been doing some exercises of C but I really don't understand why dev C++ is returning this error.
I already tried to do many things like to change the reference including a point and other things.
C:\Users\ANONYM~1\AppData\Local\Temp\ccguUdp9.o ordenacao.cpp:(.text+0x128):
undefined reference to `pesquisar_bin(int, int, int, int)'
\Mac\Home\Desktop\EXERCICIOS ED\collect2.exe [Error] ld returned 1
exit status
Your declaration and use of pesquisar_bin, does not match your implementation. As #JMichelB points out, vetor is declared to be an int and you pass it an int when calling pesquisar_bin, but your implementation defines vetor as an int[]. In the absence of an MCVE, that's the best we can surmise at this point in time.
Your implementation of pesquisar_bin is ignoring the vetor parameter and using the vet variable from file scope instead. The code is a mess due to your thrashing about and not actually posting an MCVE. Pass vet to pesquisar_bin and change the implementation to use the vetor parameter.

‘valor’ undeclared (first use in this function)

#include<stdio.h>
#include"push.c"
#include"pop.c"
#include"listadopila.c"
#include"structpila.c"
int main ()
{
struct pila valor;
void push();
int pop();
void listado();
int opcion=0;
valor.tope= -1;
int continuar;
printf ("=====ESTRUCTURA DE PILA=====\n\n");
do
{
printf ("Ingresa tu opcion:\n");
printf ("1) Para push\n");
printf ("2) Para pop\n");
printf ("3) Para mostrar tu pila\n");
printf ("4) Para salir.\n");
printf ("\n");
printf ("Ingresa tu opci%cn\n",163);
scanf("%d", &opcion);
switch(opcion)
{
case 1:
push(valor);
break;
case 2:
pop(valor);
break;
case 3:
listado(valor);
break;
default:
printf("Opción no válida.\n");
}
printf("\n¿Desea continuar comprando? Pulse cualquier tecla para si y N para no: ");
getchar();
scanf("%d",&continuar);
continuar=getchar();
}
while(continuar!='n'&&continuar!='N');
}
In other file, I define the struct like this:
struct pila
{
int pila[5];
int tope;
}valor;
And my functions are like this:
int pop()
{
int numero;
if (valor.tope==- 1)
{
printf ("La pila esta vacia.\n");
return (valor.tope);
}
else
{
numero=valor.pila[valor.tope];
printf("El elemento que haz eliminado es= %d", valor.pila[valor.tope]);
valor.tope=valor.tope -1;
}
return(numero);
}
I've tried changing the struct inside and outside the main and to write the functions into the switch case like: pop(valor); but it doesn't work either. Also in the files of each function I've tried to write the function like "int pop(struct pila valor)" but the compiler says I need to add a lenght for valor, the problem is that when I did the code in the same file the compilation finished succesfully, so the problem is when I try to link the struct with the other functions.
Any help?

undefined reference to a function call?

I think my only problem this undefined reference to...well all of my function calls. I've done functions and pointers before and tried to follow the same format but I'm lost as to what I'm doing wrong :/ I voided them all, defined my pointers, and gave them the correct types...It just says 4 errors stating "undefined reference to __menuFunction" etc...
#include<stdio.h>
void menuFunction(float *);
void getDeposit(float *, float *);
void getWithdrawl(float *, float *);
void displayBalance(float );
int main()
{
float menu, deposit,withdrawl, balance;
char selection;
menuFunction (& menu);
getDeposit (&deposit, &balance);
getWithdrawl(&withdrawl, &balance);
displayBalance(balance);
void menuFunction (float *menup)
{
printf("Welcome to HFCC Credit Union!\n");
printf("Please select from the following menu: \n");
printf("D: Make a Deposit\n");
printf("W: Make a withdrawl\n");
printf("B: Check your balance\n");
printf("Or Q to quit\n");
printf("Please make your slelction now: ");
scanf("\n%c", &selection);
}
switch(selection)
{
case'd': case'D':
*getDeposit;
break;
case 'W': case'w':
*getWithdrawl;
break;
case'b': case'B':
*displayBalance;
}
void getDeposit(float *depositp, float *balancep)
{
printf("Please enter how much you would like to deposit: ");
scanf("%f", *depositp);
do
{
*balancep = (*depositp + *balancep);
} while (*depositp < 0);
}
void getWithdrawl(float *withdrawlp, float *balancep)
{
printf("\nPlease enther the amount you wish to withdraw: ");
scanf("%f", *withdrawlp);
do
{
*balancep = (*withdrawlp - *balancep);
} while (*withdrawlp < *balancep);
}
void displayBalance(float balance)
{
printf("\nYour current balance is: %f", balance);
}
return 0;
}
Your menuFunction() getDeposit() and getWithdrawl() are defined in main()'s body. Nested functions aren't supported of ANSI-C. The easiest way to make your code work is to define functions in the global scope.
[Upd.] but don't forget to fix another bugs in your code (for example, statement variable in menuFunction() is an unresolved symbol, it must be declared as global variable or should be sent into the function as an argument. I advise you to read K&R, it is classics for C programmers!
Take your functions out of the main() function.
int main()
{
float menu, deposit,withdrawl, balance;
char selection;
menuFunction (& menu);
getDeposit (&deposit, &balance);
getWithdrawl(&withdrawl, &balance);
displayBalance(balance);
}
void menuFunction (float *menup)
{
...
...
Beside this your program has many errors. Correct them.

C/C++ function not calling a switch structure properly

so here in my code no matter how much i change i cant get it to work properly
it is supposed to go to question. that includes scanning for a int which corresponds to an option
then its supposed to call navigate now with the option declared and work with it
but no matter what option you choose it just says
sorry
#include <stdio.h>
#include <stdlib.h>
#define OPENWINDOW "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
void question(int option)
{
printf("What Would You Like To Do?\n");
printf("\t1.Add A Reminder\n\t2.View Reminders\n\t3.Manage Current Reminders\n\t4.Settings\n");
scanf("%i", &option);
}
void navigate(int option)
{
switch(option)
{
case 1:
printf(OPENWINDOW);
break;
case 2:
printf(OPENWINDOW);
break;
case 3:
printf(OPENWINDOW);
break;
case 4:
printf(OPENWINDOW);
break;
default :
printf("sorry");
question(option);
}
}
int main()
{
int option;
question(option);
navigate(option);
return 0;
}
Arguments are passed by value, not reference. So, your "option" arg is going to "disappear" soon after the function ends.
If you pass the "reference" to the var then you can use it to fill the caller variable. The following code and example fixes it.
void question(int *option)
{
printf("What Would You Like To Do?\n");
printf("\t1.Add A Reminder\n\t2.View Reminders\n\t3.Manage Current Reminders\n\t4.Settings\n");
scanf("%i", option);
}
Then you call it like this:
int option;
question(&option);
// now you can use option...
Since function can return values, you could also:
int question(void)
{
int option;
printf("What Would You Like To Do?\n");
printf("\t1.Add A Reminder\n\t2.View Reminders\n\t3.Manage Current Reminders\n\t4.Settings\n");
scanf("%i", &option);
return option;
}
// ...
int option = question();
// ...
The navigate and main using reference (pointers):
void navigate(int *option)
{
switch(*option)
{
case 1:
printf(OPENWINDOW);
break;
case 2:
printf(OPENWINDOW);
break;
case 3:
printf(OPENWINDOW);
break;
case 4:
printf(OPENWINDOW);
break;
default:
printf("sorry");
question(option);
}
}
int main(void)
{
int option;
question(&option);
navigate(&option);
return 0;
}
You need to pass option as pass-by-reference. Pass the address of option to question() and update there.
Refer the modified code.
void question(int *option)
{
printf("What Would You Like To Do?\n");
printf("\t1.Add A Reminder\n\t2.View Reminders\n\t3.Manage Current Reminders\n\t4.Settings\n");
scanf("%i", option);
}
call the question() as,
question(&option);
You need to either pass pointer of option to question or return it from the function question.
In your case value of option in main() is not changing when you read it in question(). Update your code as
int question()
{
int option;
printf("What Would You Like To Do?\n");
printf("\t1.Add A Reminder\n\t2.View Reminders\n\t3.Manage Current Reminders\n\t4.Settings\n");
scanf("%i", &option);
return option;
}
int main()
{
int option;
option = question(option);
navigate(option);
return 0;
}
You are passing "option" as call by value. Hence whatever you pass to question(). Would be lost.
Either, you return "option" from question() and pass this to navigate().
#include <stdio.h>
#include <stdlib.h>
#define OPENWINDOW "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
int question()
{ int option;
printf("What Would You Like To Do?\n");
printf("\t1.Add A Reminder\n\t2.View Reminders\n\t3.Manage Current Reminders\n\t4.Settings\n");
scanf("%i", &option);
return option;
}
void navigate(int option)
{
switch(option)
{
case 1:
printf(OPENWINDOW);
break;
case 2:
printf(OPENWINDOW);
break;
case 3:
printf(OPENWINDOW);
break;
case 4:
printf(OPENWINDOW);
break;
default :
printf("sorry");
question(option);
}
}
int main()
{
int option;
option = question();
navigate(option);
return 0;
}
~
If you do not want to use pass-by-reference, you can use pass-by-value which you are using in your code. It only needs to be implemented properly. You can change your "void question" to return a value by changing the void to "int" and issuing a return statement before the end of question function. Check code below:
#include <stdio.h>
#include <stdlib.h>
#define OPENWINDOW "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
int question()
{
printf("What Would You Like To Do?\n");
printf("\t1.Add A Reminder\n\t2.View Reminders\n\t3.Manage Current Reminders\n\t4.Settings\n");
scanf("%i", &option);
return i;
}
void navigate(int option)
{
switch(option)
{
case 1:
printf(OPENWINDOW);
break;
case 2:
printf(OPENWINDOW);
break;
case 3:
printf(OPENWINDOW);
break;
case 4:
printf(OPENWINDOW);
break;
default :
printf("sorry");
question(option);
}
}
int main()
{
int option;
option = question(option);
navigate(option);
return 0;
}
You are passing the variable option by value question(option)
You should pass option varible by reference
void question(int *option)
{
printf("What Would You Like To Do?\n");
printf("\t1.Add A Reminder\n\t2.View Reminders\n\t3.Manage Current Reminders\n\t4.Settings\n");
scanf("%i", option);
}
void navigate(int *option)
{
switch(*option)
{
case 1:
printf(OPENWINDOW);
break;
case 2:
printf(OPENWINDOW);
break;
case 3:
printf(OPENWINDOW);
break;
case 4:
printf(OPENWINDOW);
break;
default :
printf("sorry");
question(option);
}
int main()
{
int option;
question(&option);
navigate(&option);
return 0;
}
For more information regarding this have a look at this link Difference between call by reference and call by value
Because the variable option only pass its value into function question(), the variable option's value indeed is unchanged, so, maybe you should return the value of option in the function question()

Resources