trouble with functions

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.

Thanks
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!
Last edited on
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.
void means the function will not return any value. Int means the function will return an integer value, like this:

1
2
3
4
5
6
int area(int L = 0)
{
    cout << "Enter length of one side of square: " << endl;
    cin >> L; 
    return L*L; //Will return the area of the square. 
}


You can put any variable prefixed (double, float, long int etc...) and return that variable type. Void means returns no data type.
Last edited on
so in a sense you would only use void if you are returning strings or chars?
no then you would use string function or char function void means it returns nothing
Topic archived. No new replies allowed.