Output of a C program - c

I have written the following C program. The output is 32. Why is this?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define max 10+2
int main(){
int i;
i = max * max;
printf("\n%d\n",i);
return 0;
}
(I am learning C and am relatively new to it.)

#define max 10+2
This is the preprocessor. it is not smart.
it is stupid.
it just replaces text.
max*max
will resolve to
10+2*10+2
which is
10+(2*10)+2
because of operator precedence, which is
10 + 20 + 2
i.e. 32
Furthermore, you should avoid preprocessor macros whenever you can and use static const instead. You may or may not want to also consider using a const variable or an enum instead of a #define; each have their tradeoffs, refer to the similar question: "static const" vs "#define" vs "enum".
If you want to stick to preprocessor, then you could just use:
#define max (10+2)
Since parenthesised code will take operator precendence.

Since max is a macro, it gets expanded textually, so your code comes out with:
i = 10 +2 * 10 + 2;
For a macro like this, you generally want to add parentheses:
#define max (10+2)
So your expression will expand to:
i = (10+2) * (10+2);

The compiler sees this
i = 10 + 2*10 +2 = 32
You should do the macro definition like this
#define max (10+2)

Operator precedence is a funny thing. PEMDAS = Parenthises, Exponents, Multiply, Divide, Add, Subtract.
This is going to resolve to equal to 10 + (2 * 10) + 2.
First is 10*2 which equals 20.
Now it reads 10 + 20 + 2.
The rest should be clear.
You should exercise control over your arithmetics whenever desired.

Related

Output of this program is 64. Can someone explain how?

#define sqr(a) a*a
int main()
{
int i;
i = 64 / sqr(4); //answer of this expression is 64.
printf("%d", i);
return 0;
}
In this code the output is 64, and according to the rules, the expression i = 64 / sqr(4) should be solved as i = 64 / 4*4, which gives a result of 4, but the output of the program is 64. Why?
Macros are not evaluated like functions, they are expanded in place. The statement
i = 64 / sqr(4);
expands to
i = 64 / 4*4;
Both of the multiplication and division operators have the same precedence and are left-associative, so the above statement is parsed as
i = (64 / 4) * 4;
Thus, you are multiplying the result of 64 / 4 by 4, rather than dividing 64 by the result of 4 * 4.
They way to avoid precedence and associativity issues with macros like this is to enclose the expansion in parentheses:
#define sqr(a) (a * a)
By itself, though, that’s not sufficient - if you do something like sqr(1+2), that will expand to (1+2*1+2), which evaluates to 5 instead of the expected 9. You also need to parenthesize the argument(s) as well as the overall expression:
#define sqr(a) ((a) * (a))
Now your statement expands to
i = 64 / ((4) * (4));
and will evaluate to what you expect.
I'll try to keep this answer simple:
Macros is a set of code that just get replaced at the time of compilation.
Now, if you replace sqr(4) with 4*4
It becomes something like: 64/4*4.
Now, if you apply basic rule of BODMAS. It gets executed as follows:
64/4= 1616*4= 64 i.e first division with 4 then multiplication with 4 that gives 64
You need to look at the order of operations. Multiplication is done first, so it meant (64 * 4) / 4. Here's an updated version with parenshases around your macro:
#define sqr(a) ((a)*(a))
int main()
{
int i;
i = 64 / sqr(4); //answer of this expression is 4.
printf("%d", i);
return 0;
}

Why is the output 16? (C pogramming) [duplicate]

This question already has answers here:
The need for parentheses in macros in C [duplicate]
(8 answers)
Closed 2 years ago.
#include<stdio.h>
#define sqr(x) x*x
int main()
{
int a = 16/sqr(4);
printf("%d", a);
}
if I am not wrong the output should be 1
as ,a = 16/sqr(4) gives 16/16 => 1
but the output is 16
this is happening only when I take division operator(/) ,I am getting correct output when using other operators
may I know the reason? .. and thank you
16 / 4 * 4 is (16 / 4) * 4 = 16
Moral: always take care with macros. In your case you should enclose in parenthesis:
#define sqr(x) ((x)*(x))
There are still problems with this macro as it evaluates the argument twice.
For instance:
int read_int();
int a = 16 / sqr(read_int());
Will unexpectedly evaluate read_int() twice as it expands to:
int a = 16 / ((read_int() * (read_int());
The advice would be to use functions for this. Make it inline to give the compiler better chances to optimize it.
a = 16/sqr(4);
Expanded the above expression gives:
a = 16 / 4 * 4
Which is 16 based on normal mathematical order of operations.
That's why macros should always be enclosed in parentheses:
#define sqr(x) ((x) * (x))
Are you trying to make a function definiton? If yes, then i don't think it should be on a #define. Instead, make a function sqr(x). Here's how:
#include <stdio.h>
int sqr(int x)
{
return x*x;
}
int main()
{
int a = 16/sqr(4);
printf("%d", a);
}
And you'll get the result 1.
Edit: but anyway, you've already get the solution with macros. This is just another way to do what you want.

Incorrect multiplication of integers in C

A C-coded S-function in Simulink was showing incorrect behaviour and I have managed to narrow down the problem to an incorrect multiplication of integers.
At the start of the code, I have something like:
#define NRBF 21
#define NRBF1 NRBF+1
Then, in a function in the script I have:
void function_name(SimStruct *S, const int_T a)
{
...
int_T base;
base = a*NRBF1;
printf("%i\t", a);
printf("%i\t", NRBF1);
printf("%i\n", base);
..
}
Now, if a=0, NRBF=21, I have (instead of base=0)
0 22 1
If a=1, NRBF=21, I have (as expected base=22)
1 22 22
If a=2, NRBF=21, I have (instead of base=44)
2 22 43
Now, I must say I am a bit baffled. I tried to change the line of the multiplication to
base = a* (int_T)NRBF1;
but it does not solve the problem.
Any help would be greatly appreciated! Thank you!
The problem is here:
You define your macros like this:
#define NRBF 21
#define NRBF1 NRBF+1
When you write this:
base = a*NRBF1;
The preprocessor replaces NRBF1 textually with 21+1 which results in this:
base = a*21+1;
but you intended this:
base = a*(21+1);
Therefore you need to define your macro like this:
#define NRBF1 (NRBF+1)
With the macro expanded, the line looks like:
base = a*NRBF+1;
For a equal to 0, the expression is 0 * 21 + 1 which is 1.
For a equal to 2, the expression is 2 * 21 + 1 which is 43.
The solution is to put parentheses in the macro definition:
#define NRBF1 (NRBF + 1)
This is a good rule for any macro with an expression as its right-hand side.
Remember that macros are just text-substituted into the code.
It's basically calculating alright
0*21+1 = 1
The macro is expanded but the * has precedence over +. That's why this happens.
A more detail explanation would be
#define NRBF 21
#define NRBF1 NRBF+1
So what is going on
base = a*NRBF1;
or
base = a*NRBF+1
Now when a = 0 then base = 1
when a = 1 then base = 21+1 ...so on.
Correct way would be to wrap it aropund parentheses.
#define NRBF1 (NRBF+1)
Some more pitfalls:
That when you add a macro like this #define SQR(X) X*X
For some example like this where same precedence operators are there next to next then it will be problematic.
int i = 100/SQR(10);
Then it will be expanded to
int i = 100/10*10
Now same precedence operators are here executed left to right.
So it will result in i=100.
Solution same #define SQR(X) (X*X)
Also when passing an expression like this SQR(i+1) then it will be expanded to i+1*i+1=2*i+1. So a bit more correct would be
#define SQR(X) ((X)*(X))
Even with that you wouldn't be able to avoid few things if you forget one thing macro just expands - it does nothing more.
You can't use macro like this
SQR(i++) which will be expanded to ((i++)*(i++)). So you are increasing the i twice which is what you didn't mean. Moreover this will result in undefined behavior.
the define doesn't create a single value 22 but the expression 21 + 1. I wonder whether your problems go away if you change your second #define to
#define NBRF1 (NBRF + 1)

Using macro results in incorrect output when used as part of a larger math expression - why does this happen?

This is a normal C routine program which i found out in some question bank. It is shown below:
#define CUBE(p) p*p*p
main()
{
int k;
k = 27 / CUBE(3);
printf("%d", k);
}
As per my understanding and knowledge the value of K should be 1 as CUBE(3) would be replaced by 3*3*3 during preprocessing and after the subsequent compilation it would be giving the value of 1, but instead it has shown the value of 81 which has made me curious to know how it happened.
Can anyone please justify the answer of 81 to this question above.
The preprocessor merely substitutes
CUBE(3)
with
3*3*3
So you end up with:
k=27/3*3*3
Which, evaluated left-to-right with operator precedence, is in fact 81.
If you add parenthesees around the macro, you should find the results are correct:
#define CUBE(p) (p*p*p)
It would be even better to surround each instance of p with parenthesees as well, as in:
#define CUBE(p) ((p)*(p)*(p))
Which will allow you to pass expressions to the macro correctly (for example, 1 + 2).
Because of operator precedence 27/3*3*3 = 81
You could use instead:
inline int cube(int p) { return p*p*p; }
Preprocessors should be parenthesized properly. Replace it with
#define CUBE(p) ((p)*(p)*(p))
and see.
C macros do textual substitution (i.e. it's equivalent to copying and pasting code). So your code goes from:
k=27/CUBE(3);
to
k=27/3*3*3;
Division and multiplication have the same precedence and have left-to-right associativity, so this is parsed as:
k=((27/3)*3)*3;
which is 9 * 3 * 3 = 81.
This is why C macros should always be defined with liberal use of parentheses:
#define CUBE(p) ((p) * (p) * (p))
For more information, see http://c-faq.com/cpp/safemacros.html from the comp.lang.c FAQ.
Your macro is not protected. Try
#define CUBE(p) ((p)*(p)*(p))
The current macro was expanded to
k=27/3*3*3
which is ((27/3)*3)*3
Because macros are a textual substitution, that works out to:
k = 27 / 3 * 3 * 3;
Since multiplication and division happen left to right, that works out to:
k = ((27 / 3) * 3) * 3;
So, you want to change that in two ways:
#define CUBE(p) ((p)*(p)*(p))
The outer parentheses cause the multiplications to be done before any other operations.
The parentheses around the individual p's are for the case where you do:
CUBE(1 + 2);
Without those inner parentheses, operator precedence will trip you up.
k=27/CUBE(3); => k=27/3 * 3 * 3;
Do you see it? CUBE should be defined like this instead:
#define CUBE(p) ((p)*(p)*(p))
When you do macros, you have to be careful about how you place parentheses. In this case, you don't have any, so the expression becomes 27/3*3*3, which by the precedence rules of / and * becomes (27/3)*3*3.
27/3*3*3 = 9*3*3 = 81 ?
Both / and * operators have the same precedence. To execure 3*3*3 first, you shoudl enclose them in parenthesis.
#include <stdio.h>
#define CUBE(p) p*p*p
int
main ()
{
int k;
k=27/(CUBE(3));
printf("%d",k);
return 0;
}
#define CUBE(p) p*p*p
main()
{
int k;
k=27/CUBE(3);
printf("%d",k);
}
As per my understanding and knowledge the value of K should be 1 as CUBE(3) would be replaced by 3*3*3 during preprocessing
YES
and after the subsequent compilation it would be giving the value of 1,but instead it has shown the value of 81 which has made me curious to know how it happenned.
NO,
k= 27/3*3*3
=(((27/3)*3)*3) (The precedence of `*` and `/` are same but the associativity is from left to right)
=((9*3)*3) =81
Replace #define CUBE(p) p*p*p with #define CUBE(p) ((p)*(p)*(p))
its the way in which the associativity and precedence of operators is implemented.
when the expression is expanded it becomes
27/3*3*3 and not 27/(3*3*3)
now, division and multiplication both have the same precedence in C but the associativity is left to right for both.
so it can be shown as :
(27/3)*3*3 which in turn equals (9*3)*3 = 81
also, if u remember the old arithmetic rule of BODMAS(Bracket Off Division Multiplication Addition Subtraction), this is the order of precedence, then we do division first and then multiplication.
so again we get answer as 81 for 27/3*3*3.
Hi answer for this is:81
Explanation:
In step k=27/cube(3)
cube(3) is replaced by 3*3*3 by preprocessor.then above statement becomes as k=27/3*3*3
in that 27/3 expression is evaluated by c compiler(operator precedence)
the result is(27/3) :9
the statement k=27/3*3*3 becomes as k=9*3*3;
the result for above statement is 81:

Can the C preprocessor perform integer arithmetic?

As the questions says, is the C preprocessor able to do it?
E.g.:
#define PI 3.1416
#define OP PI/100
#define OP2 PI%100
Is there any way OP and/or OP2 get calculated in the preprocessing phase?
Integer arithmetic? Run the following program to find out:
#include "stdio.h"
int main() {
#if 1 + 1 == 2
printf("1+1==2\n");
#endif
#if 1 + 1 == 3
printf("1+1==3\n");
#endif
}
Answer is "yes", there is a way to make the preprocessor perform integer arithmetic, which is to use it in a preprocessor condition.
Note however that your examples are not integer arithmetic. I just checked, and gcc's preprocessor fails if you try to make it do float comparisons. I haven't checked whether the standard ever allows floating point arithmetic in the preprocessor.
Regular macro expansion does not evaluate integer expressions, it leaves it to the compiler, as can be seen by preprocessing (-E in gcc) the following:
#define ONEPLUSONE (1 + 1)
#if ONEPLUSONE == 2
int i = ONEPLUSONE;
#endif
Result is int i = (1 + 1); (plus probably some stuff to indicate source file names and line numbers and such).
The code you wrote doesn't actually make the preprocessor do any calculation. A #define does simple text replacement, so with this defined:
#define PI 3.1416
#define OP PI/100
This code:
if (OP == x) { ... }
becomes
if (3.1416/100 == x) { ... }
and then it gets compiled. The compiler in turn may choose to take such an expression and calculate it at compile time and produce a code equivalent to this:
if (0.031416 == x) { ... }
But this is the compiler, not the preprocessor.
To answer your question, yes, the preprocessor CAN do some arithmetic. This can be seen when you write something like this:
#if (3.141/100 == 20)
printf("yo");
#elif (3+3 == 6)
printf("hey");
#endif
YES, I mean: it can do arithmetic :)
As demonstrated in 99 bottles of beer.
Yes, it can be done with the Boost Preprocessor. And it is compatible with pure C so you can use it in C programs with C only compilations. Your code involves floating point numbers though, so I think that needs to be done indirectly.
#include <boost/preprocessor/arithmetic/div.hpp>
BOOST_PP_DIV(11, 5) // expands to 2
#define KB 1024
#define HKB BOOST_PP_DIV(A,2)
#define REM(A,B) BOOST_PP_SUB(A, BOOST_PP_MUL(B, BOOST_PP_DIV(A,B)))
#define RKB REM(KB,2)
int div = HKB;
int rem = RKB;
This preprocesses to (check with gcc -S)
int div = 512;
int rem = 0;
Thanks to this thread.
Yes.
I can't believe that no one has yet linked to a certain obfuscated C contest winner. The guy implemented an ALU in the preprocessor via recursive includes. Here is the implementation, and here is something of an explanation.
Now, that said, you don't want to do what that guy did. It's fun and all, but look at the compile times in his hint file (not to mention the fact that the resulting code is unmaintainable). More commonly, people use the pre-processor strictly for text replacement, and evaluation of constant integer arithmetic happens either at compile time or run time.
As others noted however, you can do some arithmetic in #if statements.
Be carefull when doing arithmetic: add parenthesis.
#define SIZE4 4
#define SIZE8 8
#define TOTALSIZE SIZE4 + SIZE8
If you ever use something like:
unsigned int i = TOTALSIZE/4;
and expect i to be 3, you would get 4 + 2 = 6 instead.
Add parenthesis:
#define TOTALSIZE (SIZE4 + SIZE8)

Resources