Saturday, June 29, 2013

C++(beginner) writing our first functions

In C++ we can write our own functions and we can use them in our code. If we need to do the same action many different times on our code , instead of copy-pasting it we can use functions.


The space I marked red is the place when we are going to write our functions. This is the form of the function

the type of the returned value       name of the function ( parameters list on our function)
{
                       actions;
                 return something;
}


every function does something and has to return something.

example we want to calculate the sum of 2 numbers

int sum(int x, int y)
{
      return x+y;
}
the parameters are x and y. When we will call this function in our code we will have to insert 2 integers in our function and we will get the sum of those numbers. X and Y can't be used outside our function, their life starts when we call our function and ends when our functions stops.

If we want our function to do something but do not return anything, in the place where for writing the return type we are writing a word "void". (just like in our main code. "Main" is a function and we write void main() to say that our main function is not going to return anything.)


Functions make our code shorter, easier for understanding. Of course function can be without any parameters.

IF YOU HAVE ANYTHING TO SAY,ASK, SUGGEST PLEASE LEAVE THAT IN COMMENTS.

No comments:

Post a Comment