Jump to content

  • Log In with Google      Sign In   
  • Create Account

Functions


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 destluck   Members   -  Reputation: 114

Like
0Likes
Like

Posted 17 July 2014 - 03:47 PM

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()
{
    ....
}


Edited by destluck, 17 July 2014 - 03:50 PM.


Sponsor:

#2 Lactose!   GDNet+   -  Reputation: 3366

Like
10Likes
Like

Posted 17 July 2014 - 04:04 PM

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.



#3 destluck   Members   -  Reputation: 114

Like
0Likes
Like

Posted 17 July 2014 - 04:06 PM

Perfect tyvm for the fast response :)



#4 aregee   Members   -  Reputation: 1022

Like
2Likes
Like

Posted 17 July 2014 - 04:45 PM

 

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


Edited by aregee, 17 July 2014 - 04:52 PM.


#5 Servant of the Lord   Crossbones+   -  Reputation: 19524

Like
12Likes
Like

Posted 17 July 2014 - 05:27 PM

'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.


It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#6 aregee   Members   -  Reputation: 1022

Like
5Likes
Like

Posted 17 July 2014 - 07:36 PM

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.


Edited by aregee, 17 July 2014 - 07:41 PM.


#7 Bacterius   Crossbones+   -  Reputation: 8856

Like
6Likes
Like

Posted 17 July 2014 - 07:53 PM

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).


The slowsort algorithm is a perfect illustration of the multiply and surrender paradigm, which is perhaps the single most important paradigm in the development of reluctant algorithms. The basic multiply and surrender strategy consists in replacing the problem at hand by two or more subproblems, each slightly simpler than the original, and continue multiplying subproblems and subsubproblems recursively in this fashion as long as possible. At some point the subproblems will all become so simple that their solution can no longer be postponed, and we will have to surrender. Experience shows that, in most cases, by the time this point is reached the total work will be substantially higher than what could have been wasted by a more direct approach.

 

- Pessimal Algorithms and Simplexity Analysis


#8 V3ntr1s   Members   -  Reputation: 402

Like
0Likes
Like

Posted 18 July 2014 - 01:49 AM

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.



#9 Shippou   Members   -  Reputation: 1523

Like
0Likes
Like

Posted 18 July 2014 - 03:52 PM

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");
   }
}


Edited by Shippou, 18 July 2014 - 03:53 PM.

 Reactions To Technologies:
1. Anything that is in the world when you’re born is normal and ordinary and is just a natural part of the way the world works.
2. Anything that's invented between when you’re fifteen and thirty-five is new and exciting and revolutionary and you can probably get a career in it.
3. Anything invented after you're thirty-five is against the natural order of things.

- Douglas Adams 2002


 





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS