tags:

views:

77

answers:

5

Hi All, I'm a newcomer to C and I have a problem when trying to call a function which is declared under the current function Ex:

void test (){ test1 ();}
void test1(){ }

I could just move test1 above test, but I have this as well :

void test () {test1 ()}
void test4 () {test ()}
void test3 () {test4 ()}
void test1 () {test3 ()}

So do you see that If I moved test() I will have the same problem for test4 () ? What could I do ?

Thanks

+1  A: 
void test();
void test1();
void test3();
void test4();

void test () {test1 ()}
void test4 () {test ()}
void test3 () {test4 ()}
void test1 () {test3 ()}

In C, you can't use a function unless it is defined before your function. This is how C works. In most other languages the compiler takes care of that. This is called forward declaration. You are just telling the compiler if you see test, test1, test3, test4 in my code don't produce an error, because these functions are defined elsewhere not before my function.

AraK
It's not required to _define_ a function before the call, it's required to _declare_ it. And even then, if you don't declare it, it will be implicitly declared as int function(); which is OK (but not good practice) if that declaration is compatible with the definition.
caf
I meant if you don't want to declare it you have to define it before your function.
AraK
+5  A: 

C will parse your file from top to bottom. It needs to at least understand the signature of a function before it can verify it's use. This is why you are running into the problem you have.

If you want to tell C about a function before it's defined you need to prototype the function. This is essentially adding the signature of the function to the file for C to process.

For example you can prototype test1 with the following

void test1();

Then you can call it before it's defined

void test1();
void test() { test1(); }
void test1() {}
JaredPar
A: 

You can declare function prototypes:

void test();
void test1();
void test3();
void test4();

void test () {test1 ();}
void test4 () {test ();}
void test3 () {test4 ();}
void test1 () {test3 ();}
Karl Voigtland
A: 

you first let compiler know the function exist :)

Jace Jung
+2  A: 

What you need to do is "forward declare" your functions before defining them. As in:

// Declarations
void test();
void test1();

// Definitions
void test()
{ 
   // definition using test1
}

void test1()
{
   // definition using test
}
Michael Aaron Safyan