
- Forum
- Programming Talk
- C and C++
- how is the precedence and associativity?
how is the precedence and associativity?
This is a discussion on how is the precedence and associativity? within the C and C++ forums, part of the Programming Talk category; Hi, in an interview question i was asked following question #define multiply(x) x*x main() { int result; result = multiply(2) ...
-
how is the precedence and associativity?
Hi,
in an interview question i was asked following question
#define multiply(x) x*x
main()
{
int result;
result = multiply(2) + 1;
}
what is the result value?
i told the answer is 5 since the macro gets expanded as 2*2+1
and here the multiplication takes first and addition latter.
but the interviewer said ans is 6 since the evaluation takes place from Left to right so first addition and then multiplcation.
i am not sure now what is correct ? i think * and + have L to R associativity and * has higher precedence.
Can someone correct me if i am wrong?
thanks a lot in advance
-
Answer to your question
Hi,
You are correct. It so happens that
result = multiply(2) + 1;
first multiply(2*2) happens and 1 gets added to it.
and the answer is 5. not 6. so u are correct.
Gayatri
-
The associativity for +,* is all from left to right and * takes precedence over +. So your approach of 2*2+1 giving 5 is prefect. Your answer is perfectly correct.
-
12-27-2010, 07:59 AM #4
- Join Date
- Dec 2010
- Answers
- 32
you are correct indeed....
1st it will be multiplied then addition.......you can check the answer if you have got scintific calculator....(2*2)+1
it will generate 5 output...
-
Sponsored Ads

Reply With Quote





