saving . . . saved [Not Related to Video] has been deleted. [Not Related to Video] has been hidden .
[Not Related to Video]
Title
Question

<span style="color:#935690;">#include</span><stdio.h>
<span style="color:#935690;">#define</span> PRODUCT(n) n*n
<span style="color:#935690;">void</span> main()
{
<span style="color:#935690;">int</span> a;
a=<span style="color:#339966;">64</span>/PRODUCT(<span style="color:#339966;">4</span>);
<span style="color:#577299;">printf</span>(<span style="color:#E91E64;">"%d"</span>,a);
}              

On compiling above program my gcc compiler gives OUTPUT: 64

Which is wrong output it should be 4 according to definition.

Why it is not considering PRODUCT (4) ?

(QUESTION: B.TECH FIRST YEAR RCS-101 AKTU 2017-18)


C-and-Cpp Understanding-Pointers 05-06 min 50-60 sec 22-04-20, 10:38 a.m. zubeen

Answers:

Hi,

When you define mathematical expressions you need to provide brackets that follow BODMAS rule; that is the best practice.Here what is happening is that the operation a = 64 / PRODUCT(4); is getting translated to 64 / 4*4, which in interpreted as (64/4)*4 == 64.

Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.

Cheers!
22-04-20, 1:07 p.m. vishnuEaswaran
Thank u very much....
22-04-20, 1:15 p.m. zubeen
The rule is not entirely similar to BODMAS.. have a look at the standard rules here 
- <a href="https://en.cppreference.com/w/c/language/operator_precedence">https://en.cppreference.com/w/c/language/operator_precedence</a>
- <a href="https://www.tutorialspoint.com/cprogramming/c_operators_precedence.htm">https://www.tutorialspoint.com/cprogramming/c_operators_precedence.htm</a>
22-04-20, 1:30 p.m. vishnuEaswaran
Ok
22-04-20, 1:37 p.m. zubeen
Thanks again
22-04-20, 1:38 p.m. zubeen

Login to add comment


When you define mathematical expressions you need to provide brackets that follow BODMAS rule; that is the best practice.Here what is happening is that the operation a = 64 / PRODUCT(4); is getting translated to 64 / 4*4, which in interpreted as (64/4)*4 == 64.

Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.

22-04-20, 3:49 p.m. arunprasadchamy@gmail.com


When you define mathematical expressions you need to provide brackets that follow BODMAS rule; that is the best practice.Here what is happening is that the operation a = 64 / PRODUCT(4); is getting translated to 64 / 4*4, which in interpreted as (64/4)*4 == 64.

Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.

22-04-20, 3:49 p.m. arunprasadchamy@gmail.com


Log-in to answer to this question.