The book I use to learn C++, practically explains nothing about it!
I don't want to make sections in my codes, which I have to call by using the "goto"-statement.
Please explain for me, once and for all, about function calls.
Printable View
The book I use to learn C++, practically explains nothing about it!
I don't want to make sections in my codes, which I have to call by using the "goto"-statement.
Please explain for me, once and for all, about function calls.
A function is a module in a program that structures the program and breaks it up into logical sections. Take this long main function for an example. (I know it's not long, bear with me).
That's kind of ugly and we can do better by taking the operations and breaking them up into logical parts.Code:#include <iostream>
#include <cmath>
int main ( void )
{
int n = 1, input;
std::cout<<"The number is "<< n <<"\n";
// Ask for the user to enter a number
// and add that number to n
std::cout<<"Enter a number to add\n";
std::cin>>input;
n += input;
std::cout<<"The number is "<< n <<"\n";
// Calculate n to the user selected power
std::cout<<"Enter a power to raise n to\n";
std::cin>>input;
n = pow ( n, input );
std::cout<<"The number is "<< n <<"\n";
return 0;
}
That's much easier to follow and we don't need the comments anymore because the function names perform that duty. Anytime you feel you need to use goto, you can easily add a function because they both do something similar, go there and execute that code. The difference between functions and goto is that goto doesn't come back. A function will return to the same line that you called it, thus allowing you to execute code after the call without setting another label and calling goto again.Code:#include <iostream>
#include <cmath>
void printResult ( int x )
{
std::cout<<"The number is "<< x <<"\n";
}
int getInput ( void )
{
int input;
std::cout<<"Enter a number\n";
std::cin>>input;
return input;
}
void add ( int& x )
{
x += getInput();
}
void raise ( int& x )
{
int i = getInput();
x = pow ( x, i );
}
int main ( void )
{
int n = 1;
printResult ( n );
add ( n );
printResult ( n );
raise ( n );
printResult ( n );
return 0;
}
I could go on and on about functions, so you might want to be more specific in what you don't understand. ;)
-Prelude
first of all I suggest getting a different book,
second: calling a function is simply: execution of your program jumps to a block of code, enclosed in braces {}, that begins with a desired function Name
and thus when such function finishes it returnes to the next line that followes after the original call to that function was made...
for example:
void SomeFunction()
{
// blah blah
}
int main()
{
SomeFunction();
return 0;
}
did i make it any clearer???
if you ever get into dynamic memory management and stuff like that you will learn that function calling in reality is executed differently.......however for now this idealogy is fine
Regards,
matheo917