View Full Version : C function call
Force Flow
10-14-2003, 12:21 AM
Can you call a function within a function in C?
For example:
#include < stdio.h > /*ignore spaces here*/
void call1 (int value1);
void call2 (int value2);
int main (void);
{
call1(value1);
return 0;
}
void call1 (int value1)
{
printf("%d", value1);
call2 (value 2);
return;
}
void call2 (int value2)
{
printf("%d", value2);
return;
}
DrZaius
10-14-2003, 03:31 AM
Yes you can functions within functions. However, the example you wrote won't run because "call1" calls "call2" with the parameter "value2" which doesn't exist within the scope of the the function.
Force Flow
10-14-2003, 04:42 PM
would this run?
#include < stdio.h > /*ignore spaces here*/
void call1 (int value1);
void call2 (int value2);
int main (void);
{
call1(value1);
return 0;
}
void call1 (int value1)
{
int value2;
printf("%d", value1);
call2 (value 2);
return;
}
void call2 (int value2)
{
printf("%d", value2);
return;
}
doctorgonzo
10-14-2003, 04:57 PM
No, because you don't declare the variable value1 in function main before you pass it to call1.
Also, you don't initialize any variables before you use them. Depending on the compiler you use, it may complain or it may not. In any case, it is good practice to intialize variables to some value, such as 0.
Force Flow
10-15-2003, 12:32 PM
how's that?
#include < stdio.h > /*ignore spaces here*/
void call1 (int value1);
void call2 (int value2);
int main (void);
{
int value 1;
value1=0;
call1(value1);
return 0;
}
void call1 (int value1)
{
int value2;
value2=0;
printf("%d", value1);
call2 (value 2);
return;
}
void call2 (int value2)
{
printf("%d", value2);
return;
}
What do you mean when you say " don't initialize any variables before you use them"?
doctorgonzo
10-15-2003, 12:37 PM
That looks like it will work (as long as you eliminate the spaces in "value 1" and "value 2", but I am sure that you have already done that.
What I meant when I said that was that you did this:
int value2;
call2(value2);
You are declaring value2 to be an int, but you don't set it to anything. Before you assign it a value, you use it in a function call. Not a good idea, because at that point value2 could be any arbitrary number. Some compilers will "fix" this by defaulting to 0, assuming that is what you want, but it is better to be explicit in code and not rely on the compiler.
Force Flow
10-15-2003, 12:49 PM
Okay, I think I get it now. Thanks, doctorgonzo :)
vBulletin® v3.7.0, Copyright ©2000-2008, Jelsoft Enterprises Ltd.