C++ Programming - Functions - Discussion

Discussion Forum : Functions - General Questions (Q.No. 9)
9.
Which of the following function declaration is/are incorrect?
int Sum(int a, int b = 2, int c = 3);
int Sum(int a = 5, int b);
int Sum(int a = 0, int b, int c = 3);
Both B and C are incorrect.
All are correct.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
15 comments Page 1 of 2.

Mirza Waseem Hussain said:   5 years ago
If you assign default value to an argument, the subsequent arguments must have default values assigned to them, else you will get compilation error.
(3)

Raksha G said:   9 years ago
Correct answer is A because default arguments should start from right.
(2)

Roopam said:   1 decade ago
Correct answer is A. Because in default argument we give value from right to left in function argument that's why D is wrong.

Ex.
int sum(int a, int b=2 ,int c=8);
is right?

int sum(int a=3, int b, int c=4);
is wrong?
(1)

Satyanarayana said:   1 decade ago
Default arguments must be at trailing side only or all arguments must be default arguments.

MAYSON KALARIKKAL said:   1 decade ago
Arguments are defaulted from right to left but c++ expects that only the arguments on the right hand side can be defaulted.
Eg:
int f(int a, int b=10,int y=5)

when we call this function with f(25,20)
we will get a=25,b=20 and y=5

Manoj Tiwari said:   1 decade ago
Correct Answer is A, not D. Please refer page No. 132 of "The C++ Programming language" by Bjarne Stroustrup. It states that: It is possible to provide default arguments for trailing arguments only.

Anurag Kumar said:   1 decade ago
During prototype declaration of a function default argument should be in right hand side in the parameter list.

Varun Girdhar said:   1 decade ago
There are two rules you must be aware of when using default arguments. First, only trailing arguments may be defaulted. That is, you can't have a default argument followed by a non-default argument. Second, once you start using default arguments in a particular function call, all the subsequent arguments in that function's argument list must be defaulted (this follows from the first rule).

Vinayak Naik said:   1 decade ago
My question goes to @Varun Girdhar, first rule is understood but in the second rule there is a query. As you can see in option C, default argument int b is followed by non-default argument int c = 3. So that contradicts rule 2 of all the subsequent arguments in that function's argument list must be defaulted (this follows from the first rule). Correct me if I am wrong.

Sonu Rajpoot said:   1 decade ago
Arguments are defaulted from right to left but c++ expects that only the arguments on the right hand side can be defaulted.

Only trailing arguments may be defaulted or all arguments may be defaulted.

Ex:

void show(int a, int b=10, int c=20)
void show_1(int a=1, int b=3, int c=5)


Post your comments here:

Your comments will be displayed after verification.