Divide code into function or not ?

Hello :)
I just wrote a big program(for me it seems big) and wonder if I should divide instruction blocks in separate function or leave all in the main function. With everything being in the main function, the code looks a little hard to read with a lot of for's and if's.
If dividing the code in more functions, I have either to use global variables or to pass the required variables through reference or pointers to the function. From what I've read, global vars are not a good idea, for a variety of reasons. Also, passing by reference/pointer would also create new variables and use therefore more memory (?).

So it seems I have to choose between an odd looking code and less memory consumption and a good looking code and more memory consumption. What would be your advice ?
closed account (EwCjE3v7)
It's you choice, I personally would just equal it out, and compilers usually replace a reference with the actual object. That would be my choice.

It would be nice to hear other people's opinions, to see if they have anything else to add.
The primary consideration should always be human readability. Don't worry about memory consumption or performance unless and until you absolutely have to. This is the first rule of program optimization.

That said, if the code is getting hard to read as you say, then bust it up into functions.
less memory consumption
You are worried about something like 1kb of excess used memory max. Also do not forget that compilers are pretty good at optimizations. So your worries about speed and memory consumptions are pointless.

Any function which large than 30 lines is a good candidate for extract method:
http://sourcemaking.com/refactoring/extract-method

Try to minimize passed variables. Prefer passing primitive types by value and complex by const reference. Avoid modifying passed values if you can. Prefer functions with single return type. If you need to return two values, use std::pait/tuple or gather your values in struct. Or just make a class which will handle invariants by itself.
don 't worry about performance. this still just a console application. when you will write games with 3d graphics you should worry about performance.

but in my opinion use functions. i used functions in my code look at it . if it was all in the main function it would be confusing and unreadable even if i coded it.

imagine this code without functions !
so i suggest to use functions in your programs and don 't worry about performance or memory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>

int menu (void);

char square[10] = {'o','1','2','3','4','5','6','7','8','9'};

using namespace std;

string y_o_n;
int placeBet;
int money = 200;
int winner2;
int winner;
int userChoice;
int userNumber;
int pcNumber = 0;
int numofguesses;
int usercalculator;
double usercalculatorinput1 , usercalculatorinput2 , sum;

double calculator(void);
void tictactoe (void);
string yesorno(void);
int init (void);
int rand_num(void);
int race (void);
int bet (void);

int main (void)
{
    cout<<" \t \t CODED BY : GILBERT SASSINE \n \n";
    cout<<"choose a number \n \n";
    menu();
    switch (userChoice)
    {
    case 1 :
         bet();
         race();
        break;
    case 2 :
        rand_num();
        break;
    case 3 :
        tictactoe();
    case 4 :
        calculator();
    }
    return 0;
}
int menu ()//menu function//////////////////////////////////////////////////////////////////
{

    cout<<"1) race "<<endl
        <<"2) Number guessing game"<<endl
        <<"3) tic tac toe"<<endl
        <<"4) Calculator"<<endl
        <<"5) Quit "<<endl;

    cin>>userChoice;
    return userChoice;
}

int race ()//if the user chose 1/////////////////////////////////////////////////////////////////
{
    srand (time (0));
    winner = rand () % 3 + 1;

 system ("cls");
cout<<"welcome to the race! \n"
    <<"and the snails are off! \n";

Sleep (2000);


cout<<"and the winner is snail "<<winner<<"\n";

if (winner == winner2)
{
    cout<<"you won ! \n";
    money = money + placeBet;
    cout<<"balance : $"<<money<<"\n";
}
else
{
    cout<<"you lost \n";
    money = money - placeBet;
    cout<<"balance : $"<<money<<"\n";
}
yesorno();
return winner;
}
int bet ()//function that asks the user if he wants to continue or not///////////////
{
    cout<<"choose your snail number \n";
    cin>>winner2;
    cout<<"how to much do you want to bet on your snail? "<<endl;
    cout<<"you have $"<<money<<endl;
    cin>>placeBet;
    return winner2;
}
//if the user chose 2///////////////////////////////////////////////
int rand_num(void)
{
   init();
   cout<<"i have picked a number between 1 and 50"<<endl;
   for (numofguesses=0 ; pcNumber != userNumber ; numofguesses++)
{
cout<<"what would you like to guess? \n";
cin>>userNumber;

if(userNumber < pcNumber)//checks if the number picked is low

  cout<<"too low \n";

else if (userNumber > pcNumber)//checks if the number picked is high

  cout<<"too high \n";

}
cout<<"you guessed it! it took you "<<numofguesses<<" guesses \n";
yesorno();

return numofguesses;
}


int init ()//seed the generator and choose a random number///////////////////////////
{
srand (time(NULL));
pcNumber = rand () % 50 +1;
return pcNumber;
}
string yesorno()//functions that asks the user if he want to continue .i use it in the 3 choices in the menu.
{
    cout<<"do you want to continue? [y]es - [n]o"<<endl;
    cin>>y_o_n;

if (y_o_n == "y")
{
    Sleep (2000);
    system ("cls");
    main();
}
else if (y_o_n == "n")
{
    cout<<"press 3 :"<<endl;
    Sleep (2000);
    system ("cls");
    menu();
}
return y_o_n;
}
int checkwin()
{
	if (square[1] == square[2] && square[2] == square[3])

		return 1;
	else if (square[4] == square[5] && square[5] == square[6])

		return 1;
	else if (square[7] == square[8] && square[8] == square[9])

		return 1;
	else if (square[1] == square[4] && square[4] == square[7])

		return 1;
	else if (square[2] == square[5] && square[5] == square[8])

		return 1;
	else if (square[3] == square[6] && square[6] == square[9])

		return 1;
	else if (square[1] == square[5] && square[5] == square[9])

		return 1;
	else if (square[3] == square[5] && square[5] == square[7])

		return 1;
	else if (square[1] != '1' && square[2] != '2' && square[3] != '3'
                    && square[4] != '4' && square[5] != '5' && square[6] != '6'
                  && square[7] != '7' && square[8] != '8' && square[9] != '9')

		return 0;
	else
		return -1;
}
void board()
{
	system("cls");
	cout << "\n\n\tTic Tac Toe\n\n";

	cout << "Player 1 (X)  -  Player 2 (O)" << endl << endl;
	cout << endl;

	cout << "     |     |     " << endl;
	cout << "  " << square[1] << "  |  " << square[2] << "  |  " << square[3] << endl;

	cout << "_____|_____|_____" << endl;
	cout << "     |     |     " << endl;

	cout << "  " << square[4] << "  |  " << square[5] << "  |  " << square[6] << endl;

	cout << "_____|_____|_____" << endl;
	cout << "     |     |     " << endl;

	cout << "  " << square[7] << "  |  " << square[8] << "  |  " << square[9] << endl;

	cout << "     |     |     " << endl << endl;
}
void tictactoe (void)
{



int checkwin();
void board();

	int player = 1,i,choice;

	char mark;
	do
	{
		board();
		player=(player%2)?1:2;

		cout << "Player " << player << ", enter a number:  ";
		cin >> choice;

		mark=(player == 1) ? 'X' : 'O';

		if (choice == 1 && square[1] == '1')

			square[1] = mark;
		else if (choice == 2 && square[2] == '2')

			square[2] = mark;
		else if (choice == 3 && square[3] == '3')

			square[3] = mark;
		else if (choice == 4 && square[4] == '4')

			square[4] = mark;
		else if (choice == 5 && square[5] == '5')

			square[5] = mark;
		else if (choice == 6 && square[6] == '6')

			square[6] = mark;
		else if (choice == 7 && square[7] == '7')

			square[7] = mark;
		else if (choice == 8 && square[8] == '8')

			square[8] = mark;
		else if (choice == 9 && square[9] == '9')

			square[9] = mark;
		else
		{
			cout<<"Invalid move ";

			player--;
			cin.ignore();
			cin.get();
		}
		i=checkwin();

		player++;
	}while(i==-1);
	board();
	if(i==1)

		cout<<"==>\aPlayer "<<--player<<" win ";
	else
		cout<<"==>\aGame draw";
   Sleep (2000);
   system ("cls");
   menu();
	cin.ignore();
	cin.get();
}
/**************************************************************************
                    CALCULATOR FUNCTION
                    MULTIPLICATION - ADDITION
                        SUBTRACTION
***************************************************************************/

double calculator (void)
{
    system ("cls");

    cout<<"1) addition"<<endl
        <<"2) subtraction"<<endl
        <<"3) multiplication"<<endl;

    cin>>usercalculator;
    system ("cls");

if (usercalculator == 1)
{
   cout<<"enter 2  numbers: "<<endl;
    cout<<" \t";cin>>usercalculatorinput1;cout<<"\n \n";
    cout<<"+\t";cin>>usercalculatorinput2;cout<<"\n \n";

Sleep (1000);
system ("cls");
    sum = usercalculatorinput1 + usercalculatorinput2;
    cout<<" \t"<<usercalculatorinput1<<"\n \n"
        <<"+\t"<<usercalculatorinput2<<"\n \n"
        <<"____________________"<<"\n \n"
        <<" \t"<<sum<<"\n \n";
}
else if (usercalculator == 2)
{
cout<<"enter 2  numbers: "<<endl;
    cout<<" \t";cin>>usercalculatorinput1;cout<<"\n \n";
    cout<<"-\t";cin>>usercalculatorinput2;cout<<"\n \n";

Sleep (1000);
system ("cls");
    sum = usercalculatorinput1 - usercalculatorinput2;
    cout<<" \t"<<usercalculatorinput1<<"\n \n"
        <<"-\t"<<usercalculatorinput2<<"\n \n"
        <<"____________________"<<"\n \n"
        <<" \t"<<sum<<"\n \n";
}
else if (usercalculator == 3)
{
    cout<<"enter 2  numbers: "<<endl;
    cout<<" \t";cin>>usercalculatorinput1;cout<<"\n";
    cout<<"*\t";cin>>usercalculatorinput2;cout<<"\n";

Sleep (1000);
system ("cls");
    sum = usercalculatorinput1 * usercalculatorinput2;
    cout<<" \t"<<usercalculatorinput1<<"\n \n"
        <<"*\t"<<usercalculatorinput2<<"\n \n"
        <<"____________________"<<"\n \n"
        <<" \t"<<sum<<" \n \n";
}
return sum;
}


Also, the process of breaking down a procedure into discreet logical functions will often clarify the solution and make you restructure it in a way which is inherently more efficient.
is there an advantage of using pointers over references
Note that there is three different entity which can be represented as pointer:
Pointer to object: You can pass a null pointer to denote that there is no object (there is better ways and anyway you should use smartpointers instead)
Pointer to array first element: only way to pass array of undetermined size in function (better to pase safer containers by [const] reference)
Iterators to array elements (use containers and supplied iterators instead)

Generally you should use pointers when you have to. Use references and value semantic otherwise.
Thanks for the opinions.
Fr0zen1, you said that the compilers usually replace a reference with the actual object. That means that no additional variables are created ?

I'll split the code in functions than. Just to be sure, is there an advantage of using pointers over references ? I would prefer to use references because they just look better and easier to use.

I know that creating new vars won't affect the performance, since I only handle ints, strings, and chars. But I just want to build healthy programming habits.

*Edit: I deleted my previous post, because new posts were written while I was writing it.
Thanks MiiNiPaa, understood.
Last edited on
Modern compilers pass arguments via registers (although this is machine dependent), so as others have said worrying about memory usage is pointless.

If as you say this is a "big" program and it is all in main, then yes, it absolutely should be broken up.

1) Look for blocks of code that are repeated. If you do the same thing more than once, then those lines are candidates to make a function.

2) Look for blocks of code that have a concise purpose. Moving these lines (even if they aren't repeated) to a well named function makes it clearer what your program is doing.
if you can use pointers, than use it !
it 's very important.
@xxgixxx - If you're coding in C++, the preferred style is to use references. Pointers are a legacy from C.

These is no difference in performance. When something is passed by reference, the compiler will pass a pointer.
Topic archived. No new replies allowed.