Anyone out there that can help me understand functions, how to use them, and how to build them?
I just finished a semester of intro to c++ and Im having a hard time getting functions. I was hoping someone out there knew how to explain them better than my instructor. It was definitely my weak point.
A function is just a way of arranging code. For example:
1 2 3 4 5
int main()
{
//put lots of code here.
//which becomes very unreadable very quickly
}
You can instead do this:
1 2 3 4 5 6
int main()
{
//Just write a few function calls here.
functionone(); //The code is sectioned nicely into blocks
functiontwo(); //which are the functions
}
So a function is just for arranging code. To declare a function is easy, you do it all the time! int main() is a function. You simply do this:
1 2 3 4
void functionone()
{
//Put all the function's code in here.
}
And then call this function from main(), as in the example above. Example usage:
No function:
1 2 3 4 5 6 7 8 9
int main()
{
int x = 0, y = 0;
cout << "Enter value for y: ";
cin >> y;
x = y * y;
cout << x << endl;
return 0;
}
With function:
1 2 3 4 5 6 7 8 9 10 11 12 13
void functionone();
int main()
{
functionone();
return 0;
}
void functionone(int y = 0, int x = 0)
{
cout << "Enter value for y: ";
x = y * y;
cout << x << endl;
}
Here, it doesn't look so useful, but when programs get bigger, functions become not just useful, but necassary!
whats the purpose of void and what other prefixes would i see? I'll read my book and try to learn more on my own but its supper helpful when someone knows how explain it more clearer.