Exforsys
+ Reply to Thread
Results 1 to 4 of 4

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

  1. #1
    Rani_2006 is offline Junior Member Array
    Join Date
    Feb 2007
    Answers
    1

    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


  2. #2
    hvg_99 is offline Junior Member Array
    Join Date
    May 2007
    Answers
    9

    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


  3. #3
    Ralph is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    114
    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.


  4. #4
    Manyamanas is offline Member Array
    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



Latest Article

Network Security Risk Assessment and Measurement

Read More...