Functions

Started by
7 comments, last by RLS0812 9 years, 9 months ago

Alright im not to sure if im using the right terms. Anyhow i wanted to know if there is a difference in declaring/initializing a function before the main or after it.

- Is it better to declare it before main or after?

- What affect does it cause?

example:


// function delcared before main()
char askYesNo1()
{
    .........
}


// main function
int main()
{
return 0;
}





// function delcared after main()
char askYesNo2()
{
    ....
}

Advertisement

With your current code, you can only call askYesNo1() from inside main. You can't call askYesNo2().

This is because main hasn't heard about askYesNo2() yet -- it comes after, after all!

You can keep the order you want, and still make main able to call askYesNo2() by forward declaring it higher up, like so:

char askYesNo1()
{
    // ...
}
 
char askYesNo2(); //Declaration, just lets rest of code know that a function with this signature exists and can be called
 
int main()
{
    return 0;
}
 
char askYesNo2() //Definition, containing the code that will actually run
{
    // ...
}

How you order functions is just for organization.

Hello to all my stalkers.

Perfect tyvm for the fast response :)

Alright im not to sure if im using the right terms. Anyhow i wanted to know if there is a difference in declaring/initializing a function before the main or after it.

- Is it better to declare it before main or after?

- What affect does it cause?

example:


// function delcared before main()
char askYesNo1()
{
    .........
}


// main function
int main()
{
return 0;
}





// function delcared after main()
char askYesNo2()
{
    ....
}

If you do like this:


char askYesNo1();
char askYesNo2();

// main function
int main() {
 return 0; 
}

char askYesNo1() { .... }
char askYesNo2() { .... }
You can have main() on top, and everything after, if you want, it is really the 'proper' way to do things. How would the compiler know what functions you are having if you are not telling the compiler somehow, unless the compiler would do a two-pass operation?

http://en.wikipedia.org/wiki/Function_prototype

'main()' is a function like any other function. The rules Lactose! and aregee explained above apply to any function. FunctionA() can't use FunctionB() unless FunctionB() is declared before FunctionA() is defined (there are some exceptions to this though).

The same thing applies to variables and variable types (like structs, classes, and enums).

You can't do this:


int y = x; //'x' hasn't been created yet!
int x = 0; //This needs to be above 'y = x'.

And you can't do this:


MyStruct foo; //'MyStruct' hasn't been defined yet!

struct MyStruct
{ ... };

And you can't do this:


void MyFunctionA()
{
    MyFunctionB(123); //'MyFunctionB' hasn't been declared yet!
}

void MyFunctionB(int)
{
...
}

Declaration means you declare to the compiler that something with that name exists.
Definition means you define the actual details of that named thing.

Declarations:


struct MyStruct;
int MyFunction(int x);

Definitions:


struct MyStruct
{
    int abc;
};

int MyFunction(int x)
{
    //... 
    return x;
}

Definitions also declare, so you don't need to do this:


//Not necessary here:
//    int MyFunction(int x) 

//This serves as both a definition and a declaration:
int MyFunction(int x)
{
    //... 
    return x;
}

Since definitions are also declarations, standalone declarations without definitions are also called pre-declarations (because they come before the full definition).

To use a function, the code only needs to be able to 'see' the declaration.

To declare a variable (like 'MyStruct foo'), the code must be able to 'see' the full definition of the variable type.

To declare a reference or pointer to a variable type (like 'MyStruct &ref'), only the declaration of that variable type is needed.

For the code to 'see' definitions or declarations, the definition or declaration must be vertically higher up the .cpp file.

Usually, function declarations are put in .h files, that are #included at the top of .cpp files.

When you #include a .h file (or any file type), it is basically copy+pasted into the .cpp file, so the function declarations in the .h file are now 'in' the .cpp file and can be seen by code vertically lower down the page.

I was going to elaborate a bit more than I did, but I had too many distractions around me when I posted, so it was hard to think. Servant of the lord filled in a lot more than I would think about too.

I just wanted to add that if you are thinking that you will skip declaring functions, and just put everything above each other, consider this example:


int functionA(int count) {
  count--;
  count = functionB(count);
  return count;
}

int functionB(int count) {
 if (count > 0) functionA(count);
 return count;
}

void main(){
 functionA(10);  //Yes you can call functions that return some value, without keeping the value.
}

Here functionA needs to be above functionB, but functionB needs to be above functionA. This is obviously impossible. I know that this exact example is artificial and silly, but there are times where you can't avoid it. I am not sure if it only happens with recursions, but I couldn't come up with any better examples right now.

To solve this problem, you just add the declarations for the functions at the top:


void main();
int functionA(int);        //The only thing C/C++ cares about, is the size of the input variable
int functionB(int count);  //But for us humans, it is easier to read if you also add the name

You can think of it like this:

Pretend that you are reading your own source code one line at the time from the top, evaluating what is happening as you go through the lines. You know nothing about anything you haven't read yet. (Ignore the fact that you actually wrote the code and _do_ know for this exercise.) Then you see that there is a functionA, so you start processing that function. Inside, there is a call to functionB, but you have never heard of such a function. What does it do? How many parameters does it take? What size are those parameters? What does it return? (Note that the return value is not part of the signature at link-time, but that is a different concept, see function overloading.)

You don't know any of those things. The same goes for the compiler. That could be solved by having one pass just to collect this information, before the real compilation phase. Another solution is to do what the designers of C did - add prototyping to the language. Then you can do both things you needed two passes for in just one pass.

I haven't seen it explicitly mentioned here but thought it might be useful to the OP as it may not be necessarily obvious to newbies - the important thing you must be aware of is that you don't need to know how a function is implemented in order to be able to call it. This is possibly the first introductory example of abstraction through separation of the interface (prototype, what it is/does) and implementation (definition, how it does it).

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

For readability sake I put my function declaration before main and definition after main

If you have more then few functions try to organize them into struct or class with a multiply files.

Good practice is to put only declaration in .h (header) file and definition in .cpp which means that every header file should have .cpp file, note that this is not cpp where your main() function is.

General example:


//example.h file
class example    //declaring class that will contain functions we need
{
functionA();    //declaring only function prototype
functionB();
};

//example.cpp file
example::functionA()
{
/*your function definition goes here*/
}
example::functionB()
{
/*your second function definition goes here*/
}

//main.cpp file
#include"example.h"   //including header file will allow us to use our class in main()
int main()
{
example one;   //creating object called "one" from a class "example"
one.functionA();     //calling a function through object we created
one.functionB();
...
..
}

BR.

This is one reason why I like Java - you do not have to declare functions before use ...


public class SomeClass{
 
   public void SomeClass(){
        saySomething();
   }
   public void saySomething(){
        System.out.println("Hello World");
   }
}

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

This topic is closed to new replies.

Advertisement