Correct usage of functions

Hello everyone,

From the moment I learned how to use functions, I've kind of been wondering whether I'm using them correctly or not. Considering I'm learning everything on my own, I don't have much reference to go by, other than things I find in a book.

What I wonder is if it is good programming practice to keep a particular task in a separate function? How do you decide what to keep, and what to do separate?

I find myself doing even menial tasks like:
1
2
3
4
5
6
7
8
9
10
void printTitle()
{
   //some title here 
}

int main ()
{
   printTitle();
   //more code
}


I could just have placed that thing inside the main() function. But for some reason I prefer to have as much of the real code outside of main(). I do not know why though, I just think it looks more organized that way.

Thing is, even if there are no disadvantages to it, is it still a good practice to do so? I don't want to end up doing this all the time and then having to unlearn it when I do start earning money for this.

I may be to hasty on this, as OOP is in the next chapter. It just bothers me when I write my code now :D
Last edited on
well it is quite nice if you use the function multiple times in your main. otherwise you allways have to rewrite it.
Hi sfBlackfox,

Everything you have said is right. And it is very good practice.

Taking code out of main makes things much clearer.

1
2
3
4
5
6
7
8
9
10
void ShowMenu()
{
   //print 20 lines of menu here
}

int main ()
{
   ShowMenu();
   //more code
}



One big advantage of functions is they allow you to reuse code.

A good style point is to put your function declarations before main, and the definition of them after main.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void ShowMenu();
double CircleArea( double radius);
int main ()
{

double Area= 0.0;  //description of what this local variable is 

   ShowMenu();
  Area = CircleArea(10.0);   //more code
}
void ShowMenu()
{
   //print 20 lines of menu here
}

double CircleArea( double radius)  {
double Area = 0.0;     //description of what this local variable is 

//code in here to do calc
return Area;
}


For a program that shows a menu, you would have these functions:

ShowMenu
ProcessMenuOptions
MenuOptionA //Use a better name like PlayTicTacToe
MenuOptionB
MenuOptionC

//any other functions that are needed
Last edited on
Thanks for those replies guys.

@TheIdeasMan: I like those naming conventions you gave me. I was using "PlayTicTactToe" and the likes, and never was too sure what to name them.

One last question: I notice that most people use the UpperCamelCase, while I'm using the lowerCamelCase. Should I be using UpperCamelCase as well?
closed account (zb0S216C)
sfBlackFox wrote:
"I notice that most people use the UpperCamelCase, while I'm using the lowerCamelCase. Should I be using UpperCamelCase as well?"

You can use either; the compiler doesn't care.

Wazzal
Last edited on
Thanks
Topic archived. No new replies allowed.