C++ Programming - Functions - Discussion

Discussion Forum : Functions - Programs (Q.No. 8)
8.
What will be the output of the following program?
#include<iostream.h> 
struct MyData
{
    public:
    int Addition(int a, int b = 10)
    {
        return (a *= b + 2);
    }
    float Addition(int a, float b);
};
int main()
{
    MyData data;
    cout<<data.Addition(1)<<" ";
    cout<<data.Addition(3, 4);
    return 0; 
}
12 12
12 18
3 14
18 12
Compilation fails.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
14 comments Page 1 of 2.

Asish Satpathy said:   1 decade ago
case "cout<<data.Addition(1)<<" ";"

Here the function will carry "Addition(1,10)"
And the evaluation will be
1*=10+2;
=>1*=12
And hence a=12.

case cout<<data.Addition(3,4);

Here the function will carry "Addition(3,4)"
And the evaluation will be
3*=4+2;
=>3*=6;
And hence a=18.

Raghib said:   10 years ago
Ya "=" precedence is less than "+" or "*".

But the equation a *= b + 2 is read as a = a*b+2.

And the precedence of * is more than = . So it should be 12, 14.

Explain if anyone know this properly.

Meet Sonani said:   8 years ago
Please explain why structure can hold a function in it?

Structure can hold a group of variables, not functions. Whereas classes can hold both variables and functions.
(1)

Pooja said:   6 years ago
a*=b+2 internally it means a=a*b+2 but in this case right hand side expression execute first i.e b=4 hence 4+2=6,

Now it will be a=a*6 i.e a=3*6 hence a=18.

Mahadev said:   2 years ago
Precedence of * is more than +.

But in this case *= is used as assignment operator whose precedence is lower than + or any arithmetical operator.

Arjun said:   5 years ago
@Meet Sonani.

In C, structure can have variables only but in C++, structure can have both variables and functions.

Hari said:   8 years ago
@Raghib.

Why did you expand a *= b + 2 to a = a*b+2 before applying the precedence rule?

Can you explain it?

Mayur Shankariya said:   8 years ago
The precedence level of *= is less than + operator so,

a *= b + 2;
3 *= 4+2;
3 *= 6;
a=3*6;
a=18;

Vivek said:   1 decade ago
Because the precedence of "=" is less than "+" or "*" or any arithmetic operator.

Hardik said:   1 decade ago
Because first prefer default arguments and if not match then go for others.


Post your comments here:

Your comments will be displayed after verification.