tags:

views:

92

answers:

4
+2  Q: 

function concept

void execute(int &x,int y=100)
{
 x=x+y;
 cout<<x<<endl;
}
void main()
{
 int a=5,b=6;
 execute(b);
}

will the following program work in spite of not assigning a default value to the x(formal parameters in the fuction prototype).

+3  A: 

Yes, it will work. By not assigning the default value to x you are forcing the caller to pass a value as the parameter. When you do execute(b) in main you are binding the reference x with actual parameter 'b' and since you have not passed any value to variable 'y' the default value will be used.

Naveen
+2  A: 

Firstly, there's no such thing as "function prototype" in C++. "Prototype" is a term from C parlance, which has no meaningful application in C++. What you have here is a function declaration, which also happens to be a function definition.

Secondly, it appears you are asking whether it is required to specify default arguments for all function arguments in C++, right? If so, the answer is no, there's no requirement to specify default arguments for all function arguments.

Thirdly, it is supposed to be int main, not void main.

AndreyT
The C++ standard (§ 3.3.3) defines "function prototype scope", a scope that "terminates at the end of the nearest enclosing function declarator." I'd call that a "meaningful application." There are other references beyond that.
Matthew Flaschen
A: 

I think you're confused as to how a function works. You're passing the value for x into it (well, a reference to an int not the actual value) so ... yes, that works.

By providing a default value for y ( int y=100 ) you're making it so the function can be called without passing the second argument to it. If called with a single argument, y will be assigned the value 100.

int a=5,b=6;
execute(b);

Once inside execute(), the initial value of x is 6, and y is 100.

Brian Roach
+1  A: 

You run execute(b), meaning that execute will run b = b + 100 (y is 100 since you didn't pass it in, and it got the default value), print out 106 and b will be modified back in main, since it's taken by reference.

Eli Bendersky