Why does this happen?

From the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int proc(int x, int y = 0)
{
	return x + y;
}

int main()

{



cout << proc(5, 6);

}


Why does the assignment within function definition not occur?
Last edited on
That's not an assignment, it's a default parameter.
Ok thanks. So it is overidden. So only if i call the function with one parameter will it be used?
Yes.
Because the 'int y=0' part is not an assignment, it's a default value.

In other words, the function proc takes two arguments, x and y.
But only the first has to be explicitly passed. If you call the function with only 1 parameter, y assumes the default value of '0'. If you call the function with 2 parameters, y takes the value of the second parameter.

1
2
3
4
5
6
7
8
9
10
int proc(int x, int y=0)
{
     return x+y;
}

int main()
{
     cout << proc(1) << endl;   //same thing as proc(1,0);
     cout << proc(1,2) << endl;   //here 'y' is set to '2'
}

Last edited on
Cheers
Topic archived. No new replies allowed.