C++ Parameters and void | Sololearn: Learn to code for FREE!
- 1

C++ Parameters and void

int Para(int x, int y){ // code } What is the point of using parameters when one could write int x,int y and assign a value to it in main or inside para? Also with the void, what does it mean by “not returning anything”? I see void return data with cout.

30th Dec 2018, 1:31 PM
Jared
2 Answers
0
1) When you declare a new method you have to declare how many parameter that method will accept, or you will not be able to pass them when you call the method from main or from another method, for example I want make a method that sum 2 values: void Sum(int x, int y) { cout << x + y; } Now when i call the method from main I have to pass the two arguments that will substitute the x and y, lets say I want to sum 2 and 3, i call the sum method like this: Sum(2, 3); now the method sum will run and it will sabistitute the x with 2 and y with 3 and will print their result with cout. If i do the sum method like this: void Sum(){ cout << x + y; } and after call it: Sum(2,3); this will give a compiler error because the Sum method is declared without any parameter so you cannot call it passing arguments, you can only call it like this: Sum(); but if i do this the them Sum method will not know what x and y are meant for so we will have another error! So we use parameter when we need to create a method that need to take some argument and process it! Of course not all method needs parameter, for example: void Greet(){ cout << “welcome”; } only print the word welcome that is already defined in the method so it doesnt need to take any parameter because it already know what to do!
30th Dec 2018, 2:24 PM
Sekiro
Sekiro - avatar
0
2) void means it return no value, meaning that for example with the sum method of before: void Sum(int x, int y){ cout << x+y; } this method will only print the sum of the x and y but it will not store the result nowhere. But lets say I want to store the result of the sum in some variable I will need the method return a value, lets say an integer, and so: int Sum(int x, int y) { return x+y; } then when i call the method in main i will have a variable to store the value returned by sum method like this: int result; result = Sum(2, 5); so now result will have value of 5, because the method Sum will return the sum of 2 and 3 in form of integer (that is why I store it inside an integer variable) if the Sum method were to be void instead of int, it will return no value so the variable x will be 0! P.s.: Void does not return any data, cout is just another method the print something to the screen, but it is not returning values or datas!
30th Dec 2018, 2:25 PM
Sekiro
Sekiro - avatar