Exforsys

Online Training

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(...


Go Back   Exforsys > Programming Talk > C and C++

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 05-29-2007, 12:31 PM
Junior Member
 
Join Date: Feb 2007
Posts: 2
Rani_2006 is on a distinguished road
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
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 05-30-2007, 08:08 AM
Junior Member
 
Join Date: May 2007
Posts: 9
hvg_99 is on a distinguished road
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
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 06-02-2007, 02:05 AM
Senior Member
 
Join Date: Apr 2006
Posts: 139
Ralph is on a distinguished road
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.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -4. The time now is 09:11 AM.


Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.1.0
Copyright 2004 - 2007 Exforsys Inc. All rights reserved.