noob c++ question

1) so in c++ everything runs in order? like the compiler reads from the first line to the last, from top to bottom and execute code in that orde?
2) int main() is where everything happens? if you do not have an int main, the program does not run?
3) even if you have an int main(), it doesn't really have to do anything right? like i can have two function, int main() and sample(), int main does not have to really do anything and sample can do everything if i wanted it that way right?
1. yes and no, for example the program flow is dependent on how you right it:eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
   function4();
   function2();
   function1();
   function3();
 
   return 0;
}

void function1()
{
}
void function2()
{
}
void function3()
{
}
void function4()
{
}

But from within blocks it will execute sequentially. And code is read from top to bottom for the most part. which is why if you declare some int variables, a,b,c and then say c= a+b; and then decalare the values of a and b, you will get a compiler error: int a; a is undefined. int b: b is undefined. etc... So in this example a and b must have values first.
this is an error
1
2
3
int a,b,c;
c = a+b;
a=44; b=55;

this is right
1
2
3
int a,b,c;
a=44; b=55;
c=a+b;


2. I'm not entirely sure of whether static methods execute before main as they can do in other languages. But for the most part yes, although there may/may not be some exceptions to this rule. Hopefully someone else will expand on this:

3. Correct, you don't need anything in main except for a call to a driver function if that is what you wish.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
   function1();
   return 0;
}

void function1();
{
   function2();
   function3();
   
   MyClass mc;
   mc.doSomething();
 
 // etc ... 
Last edited on
1. gcampton: You're forgetting about control structures and jumps.
2. Libraries don't need main() because they'll be ran by programs that do have them.
3. It's possible (but not good practice) to have a fully functional program with an empty main(). It's almost a hack, really, but it's possible.
I didn't forget anything, I just gave 1 example and didn't expand on what was already a yes/no answer. I typically like to ignore "goto" and pretend it doesn't exist anyway :)

Libraries don't need main() because they can be run by programs that do, but can they run by themselves?

I typically like to ignore "goto" and pretend it doesn't exist anyway :)
What about continue, break, and return?

but can they run by themselves?
No!
concerning the question about the order that the code is executed, let's forgot about control syntax like goto and etc, just basic stuff.

1) the int main() almost must always be included right? also the int main() is the first function be executed?
2) so if code is read in order, if i have a function before int main(), would that function be executed before int main()? for ex:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int function1()
{
int x = 12;
 cout << x << endl;
}
int main()
{
 int y = 3;
 cout << y << endl;
 return 0;
}

would it display

12
3


OR
 3
12


so which one?

edit: i just ran the program and it only displays 3, meaning int main() is executed first and only code in int main() will produce output? so in order to get 12 to display, i have to call on function1() in int main()? i cannot just write it like that and expect 12 to be displayed?
the int main() almost must always be included right?
No, not always.

also the int main() is the first function be executed?
Also not always.

if i have a function before int main(), would that function be executed before int main()?
Order of definition is unrelated to order of execution.

In your example, function1() will never run. A function must be called in order to run.
@at helios, i need to call the function in int main() right, does that not mean int main() right first? say even if i had two functions before the main function, function1() and function2(). and lets say in function2() i made a call to function1(). for that call to be executed, i would have to run function2() in the first place, and for function2() to run, i have to call function2() in int main() correct? does that mean the compiler looks at int main() first?

sorry im a noob so ima bit unsure
The problem is your question was regarding C++ code, not a program. (Really my first post discussed more program execution rather than code execution) I assume this is what you we referring to anyway...

So in the case of Libraries etc. int main() is not needed. Code is code, it can be a number of different things from a class that represents a DOG, or a small database of peoples names. It can also be a full fledged program that can be compiled and executed.

For the most part, of course there is exceptions, code runs top to bottom, ignoring program flow (eg the way the programmer/s write there functions/classes/libraries). Like Helios mentioned there are also control structures. GOTO which should be ignored (because it makes for complex code stucture, and is widely considered bad practise), Break, Continue: both of which are used in a top to bottom approach, however in the case of break, will break out of the current loop and continue on.. in the case of continue it will jump back to the top of the loop, and return returns a value back to the current function or where the current block of code was called from. (main returns the value back to the operating system when the program finishes).

edit: As you are a beginner I will answer your above question as simply as possible, without trying to be semantically incorrect as it seems to get me in trouble a lot.

There are cases where main is not executed first BUT, it is up to the programmer to put these practices in place, so failing that if the programmer does not include such functions then YES main will run first so long as the program is compiled normally, and is run from the OS in a normal fashion.
As for the other questions that is right, like the above block of code I had in my first post you are able to call functions from other functions, but the functions must at one point be called from main, this is of course yet again assuming you don't have any hacks in place that disregard the use of int main(). You don't really need to have all your code in main, that is why we write libraries and classes.

I don't think Helios was disagreeing with my first post so much, but saying it definitely needed further clarification. That and I was going on the assumption you were referring to program flow, and not general code flow. Which really I should have expanded on as well.
Last edited on
closed account (j3bk4iN6)
usually with functions you list the prototype near the top after namespace and before main. That way you can keep main near the top so you don't have to go looking for it when you have alot of functions this keeps it more organized. Then the functions would follow main. a protoype is written just like the function without the block of code

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
//Ex5_01.cpp
//Declaring, defining, and using a function
#include<iostream>

using std::cout;
using std::endl;

double power(double x, int n);			//function prototype

int main(void)
{
	int index = 3;			//raise to this power
	double x = 3.0;			//different x from that in function power
	double y = 0.0;

	y = power(5.0, 3);		//passing constants as arguments

	cout << endl
		<< "5.0 cubed = " << y;

	cout << endl
		<< "3.0 cubed = "
		<< power(3.0, index);		//outputing return value

	x = power(x, power(2.0, 2.0));		//using a function as an argument. The right most in the expresion is called first and the result supplies the value
	cout << endl						//for the second argument to the leftmost call. the n argument is a type int so its converted.		
		<< "x = " << x;					//x = power(x static_cast<int>(power(2.0, 2)); avoids compilier warnings, it doesn't remove possibility of losing data

	cout << endl;
	return 0;
}

//function to compute positive integral powers of a double value
//first argument is value, second argument is power index 
double power(double x, int n) // n is specified as type int(see above)
{						//function body starts here
	double result = 1.0;		//result stored here
	for(int i = 1 ; i <= n ; i++)
		result *=x;			// x is variable ; n is the power. So x to the power of n
	return result;
}						//and ends here 
Actually, on most of the code I've seen, main() was always at the bottom. We programmers are lazy like that.
closed account (j3bk4iN6)
here's an example of how its easier to follow when someone else works on it.

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
//calculator.cpp
//keyboard string arithmatic program
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cmath>

using std::cin;
using std::cout;
using std::endl;

char* extract(char* str, int& index);		//function to extract a substring
void eatspaces(char* str);					//function to remove spaces
double expr(char* str);						//function evaluating an expression
double term(char* str, int& index);			//function analyzing a term. the second parameter is a reference.
double number(char* str, int& index);
void error(char* str, int index);			//function to identify an error
double doOperation(char* op, double value); //execute math function

const int MAX = 80;							//maximum expression length including '\0'
const double degToRad = 57.295779;			//conversion factor, degrees to radians

int main()
{
	
	char buffer[MAX] = {0};					//input area for expression to be evaluated

	cout << endl
		<< "Welcome to your friendly calculator."
		<< endl
		<< "Enter an expression, or an empty line to quit." << endl
		<< "sin(value), cos(value), tan(value) for radians." << endl
		<< "sind(value), cosd(value), tand(value) for degrees." << endl
		<< "sqrt(value) for square root. '^' is used for power." << endl
		<< "example: 2 + (2-1) / 3 * sin(6)"
		<< endl;

	for(;;)
	{
		cin.getline(buffer, sizeof buffer);		//read input line
		eatspaces(buffer);						//remove blanks from input

		if(!buffer[0])							//empty line ends here
			return 0;

		cout << "\t = " << expr(buffer)			//output value of expression
			<< endl << endl;
	}
}


//function to eliminate spaces from a string
void eatspaces(char* str)
{
	int i = 0;		//'copy to' index to string
	int j = 0;		//'copy from' index to string

	while((*(str + i) = *(str + j++)) != '\0')			//loop while character is not \0. the loop condition copies the string by moving the character at
		if(*(str + i) != ' ')							//position j to the character at position i and then increments j to the next character
			i++;										//increment i as long as character is not space
	return;	
}

//function to evaluate an arithmetic expression
double expr(char* str)
{
	double value = 0.0;			//store result here
	int index = 0;				//keeps track of current character position. initialized to zero which is the first character in string

	value = term(str, index);	//get first term. to get the value of the first term by calling the function term()

	for(;;)						//indefinite for loop; the action is determined by a switch statement, which is controlled by the current char in the string.
	{
		switch(*(str + index++))
		{
			case '\0':			//end of string
				return value;	//so return what we got

			case '+':			// + found so add in the next term
				value += term(str, index);
				break;

			case '-':			// - found so subtract the value returned by term() from the variable value
				value -= term(str, index);
				break;


			default:			//if default then the string is junk. As long as either + or - the loop continues. each call to term() moves value of index variable 
				cout << endl	//to the character following the term that was executed
					<< "Arrgh!*#!! There's an error"
					<< endl;
				error(str, index-1);
				exit(1);		//#include <cstdlib>
		}
	}
}

//function to get the value of a term
double term(char* str, int& index)
{
	double value = 0.0;			//somewhere to accumulate the result

	value = number(str, index);	//get the first number in the term

	//loop as long as we have a good operator
	while((*(str + index) == '*') || (*(str + index) == '/') || (*(str + index) == '^'))
	{
		if(*(str + index) == '*')				//if it's a multiply
			value *= number(str, ++index);		//multiply by next number

		if(*(str + index) == '/')				//if it's divide
			value /= number(str, ++index);		//divide by next number

		if(*(str + index)== '^')						// if it's exponentiation
			value = pow(value, number(str, ++index));	// raise to power of next number
	}
	return value;
}

//function to recognize a number in a string
//function to recognize an expression in parentheses or a number in a string
double number(char* str, int& index)
{
	double value = 0.0;			//store the resulting value

	 // Look for a math function name
	char op[6];
	int ip = 0;
	while (isalpha(*(str+index)))		//copy the function name
		op[ip++] = *(str+index++);
	op[ip] = '\0';						//append terminator


	// you get as many nested parentheses as you need. An example of recursion.
	if(*(str + index) == '(')			//start of parentheses
	{
		char* psubstr = 0;		//pointer for a substring
		psubstr = extract(str, ++index);//extract substring in brackets
		value = expr(psubstr);	//get the value of substring

		// If we have a math operation saved, go and do it
		if(op[0])
			value = doOperation(op, value);

		delete[]psubstr;	//clean up free store
		return value;		//return substring value
	}

	while(isdigit(*(str + index)))						//loop acumulating leading digits. isdigit(int c) returns nonzero if the argument is a digit, 0 otherwise
		value = 10 * value + (*(str + index++) - 48);	//as the number in the string is a series of digits as ASCII characters the function steps through
														//the string accumulating the value of the number digit by digit. first accumulates digits before decimal point
														//an ASCII character has ASCII value between 48, thus if you subtract the ASCII code from 0 you 
														//convert it to its equivelent digit value from 0 to 9
														
														



	if(*(str + index) != '.')	//not a digit when we get to here so check for decimal point and if not, return value
		return value;

	double factor = 1.0;		//factor decimal places for number 
	while(isdigit(*(str + (++index))))		//loop as long as we have digits
	{
		factor *= 0.1;			//decrease factor of 10
		value = value + (*(str + index) - '0') * factor;		//add decimal place.Is for fractional part so for 54, 48, 56, is 6,0,8
	}

	return value;				//on loop exit we are done
}

//function to extract a substring between parentheses
//requires <cstring> header file
char* extract(char* str, int& index)
{
	char buffer[MAX];			//temporary space for substring
	char* pstr = 0;				//pointer to new string for return
	int numL = 0;				//count of left parentheses found
	int bufindex = index;		//save starting value for index

	do
	{
		buffer[index - bufindex] = *(str + index);
		switch(buffer[index - bufindex])
		{
		case ')':
			if(numL == 0)
			{
				buffer[index - bufindex] = '\0';	//replace ')' with '\0'
				++index;
				pstr = new char[index - bufindex];
				if(!pstr)
				{
					cout << "Memory allocation failed,"
						<< " program terminated.";
					exit(1);
				}
				strcpy_s(pstr, index - bufindex, buffer);	//copy substring to new memory
				return pstr;		//return substring in new memory
			}
			else
				numL--;				//reduce count of '(' to be matched
			break;

		case '(':
			numL++;					//increase count of '(' to be matched

			break;
		}
	}while(*(str + index++) != '\0');		//loop-don't overrun end of string.

	cout << "Ran off the end of the expression, must be bad input."
		<< endl;
	exit(1);
	return pstr;
}

// Function to identify an error
void error(char* str, int index)     
{
	cout << str << endl;
	for (int i = 0; i < index; i++)
		cout << ' ';
	cout << '^' << endl;
}

// Execute math function
double doOperation(char* op, double value)
{
   if (!_stricmp(op, "sin"))		//_stricmp(); funciton compares string to "term"
      return sin(value);
   else if (!_stricmp(op, "sind"))
      return sin(value/degToRad);
   else if (!_stricmp(op, "cos"))
      return cos(value);
   else if (!_stricmp(op, "cosd"))
      return cos(value/degToRad);
   else if (!_stricmp(op, "tan"))
      return tan(value);
   else if (!_stricmp(op, "tand"))
      return tan(value/degToRad);
   else if (!_stricmp(op, "sqrt"))
      return sqrt(value);
   else
   {
      cout << "Error: unknown operation '" << op << "'" << endl;
      exit(1);
   }
   return 0;
}
Last edited on
I didn't ask for an example. I know why someone would want to do that. I'm just saying that no one does that. Not in the code I've seen, anyway.
closed account (j3bk4iN6)
I think a better reason is how the stack optimizes memory.
I'm sorry?
closed account (j3bk4iN6)
doesn't it take the compiler extra time to go though each function without prototypes when it can reference using the prototype to make it faster. sorry about that block of code.
Last edited on
No. Don't be ridiculous.
closed account (j3bk4iN6)
lol :p
closed account (j3bk4iN6)
I think I'll stick to my organization because theres a definite purpose behind it.
Actually, on most of the code I've seen, main() was always at the bottom. We programmers are lazy like that.

Really? I always put main in it's own file, and put everything else in separate source files. I hardly ever have everything in one source file, and if I do, I always organize it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>

int UH_OH_GLOBALS;

void foo();
void bar();

int main() {
    foo();
    bar();
    putchar('\n');
    return 0;
}

void foo() {
    printf("foo");
}

void bar() {
    printf("bar");
}


i.e., in the structure:
includes
macros
globals, structures, etc.
function declarations
main
function definitions


Although sometimes macros go before includes (when the file included relies on it, e.g.
1
2
#define WIN32_LEAN_AND_MEAN
#include <windows.h> 
); usually they go after for some reason.
Last edited on
Topic archived. No new replies allowed.