This question already has answers here:
The need for parentheses in macros in C [duplicate]
(8 answers)
Closed 4 years ago.
I am not able to understand this code
#define sqt(x) x*x
int main(){
print("%d",sqt(3+1));
}
Manually I am getting the output of 10. But when write the code and compile it I am getting the answer as 7. Please explain this.
Remember, since you're using a macro, 3 + 1 is not evaluated before sqt is called. x becomes 3 + 1 (not 4), then order of operation causes an unexpected answer to be produced since addition happens after multiplication.
Or in other words:
sqt(3 + 1)
expands to:
3 + 1 * 3 + 1
Then, when you evaluate this like you would any other equation:
3 + 1 * 3 + 1 // Multiplication happens first
= 3 + 3 + 1
= 7
This is a good example of why you shouldn't use macros unless they're strictly necessary, or you've made proper care to ensure that things like order of operation mistakes don't happen. As #Barmar points out this particular case can be remedied by having the macro expand to include explicit parenthesis:
#define sqt(x) ((x)*(x))
Which would cause the evaluation to differ and give a proper answer:
(3 + 1) * (3 + 1)
4 * 4
16
Related
This question already has answers here:
C macros and use of arguments in parentheses
(2 answers)
Closed 1 year ago.
I'm a beginner in programming and I have a question. Mainly, what is the difference in defining PI exactly as I state below;
#define PI (4.*atan(1))
#define PIa 4.*atan(1)
#define PIb 4*atan(1)
I have printed this code:
printf( "%lf\n", 3 / PI );
printf( "%lf\n", 3 / PIa );
printf( "%lf\n", 3 / PIb );
The results are:
0.954930
0.589049
0.000000
According to my calculator the first one is correct, and the rest should also be.
Why aren't they?
The macro is text substitution thus:
3 / PIa
is parsed as:
3 / 4.*atan(1) = (3/4.) * atan(1)
This is different from the first case where 3 / PI is expanded as:
3 / (4.*atan(1))
The similar case is for the third example:
3 / 4*atan(1) = (3/4) * atan(1)
The expression 3/4 is integer division, which result is 0.
Generally, it is strongly advised to put parentheses around the whole macro and all parameters it takes like in the following example:
#define ADD(a,b) ((a) + (b))
This question already has answers here:
C macros and use of arguments in parentheses
(2 answers)
The need for parentheses in macros in C [duplicate]
(8 answers)
Closed 3 years ago.
I find no difference between these two macros except the parentheses surrounding the macro in the first one.
Is it a matter of readability or is it a way to deal with the priority of operators?
#define TAM_ARRAY(a) (sizeof(a)/sizeof(*a))
#define TAM_ARRAY2(a) sizeof(a)/sizeof(*a)
Yes, there is a difference. The parentheses are needed so that the result of the macro is evaluated as a single expression, rather than being mixed with the surrounding context where the macro is used.
The output of this program:
#include <stdio.h>
#define TAM_ARRAY(a) (sizeof(a)/sizeof(*a))
#define TAM_ARRAY2(a) sizeof(a)/sizeof(*a)
int main(void)
{
int x[4];
printf("%zu\n", 13 % TAM_ARRAY (x));
printf("%zu\n", 13 % TAM_ARRAY2(x));
}
is, in a C implementation where int is four bytes:
1
3
because:
13 % TAM_ARRAY (x) is replaced by 13 % (sizeof(x)/sizeof(*x)), which groups to 13 % (sizeof(x) / sizeof(*x)), which evaluates to 13 % (16 / 4), then 13 % 4, then 1.
13 % TAM_ARRAY2(x) is replaced by 13 % sizeof(x)/sizeof(*x), which groups to (13 % sizeof(x)) / sizeof(*x), which evaluates to (13 % 16) / 4, then 13 / 4, then 3.
Along these lines, TAM_ARRAY would be better to include parentheses around the second instance of a as well:
#define TAM_ARRAY(a) (sizeof(a)/sizeof(*(a)))
Macros are replaced textually in an early phase of code translation. Unless side effects are specifically expected, it is very important to fully parenthesize macro arguments in the macro expansion and the macro expansion itself if it is an expression.
In the case posted, you are unlikely to have a problem because few operators have higher precedence and they would probably not be used around the macro expansion, but here is a pathological example:
TAM_ARRAY(a)["abcd"] expands to (sizeof(a)/sizeof(*a))["abcd"] whereas
TAM_ARRAY2(a)["abcd"] expands to sizeof(a)/sizeof(*a)["abcd"] which is equivalent to sizeof(a) / (sizeof(*a)["abcd"]).
Note however that an operator with the same precedence placed before the macro expansion such as % would definitely cause problems as explained in Eric Postpischil's answer.
Note also that a should be parenthesized too:
#define TAM_ARRAY(a) (sizeof(a) / sizeof(*(a)))
The way macros work is that the code is "swapped out" when compiling.
So something like
#define ADD(i, j) i + j
int k = ADD(1, 2) * 3
would be seen as: int k = 1 + (2 * 3)
Whereas,
#define ADD(i, j) (i + j)
int k = ADD(1, 2) * 3
would be seen as: int k = (1 + 2) * 3
So, there are two macros likely because of operator priority.
This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 5 years ago.
can you please explain me this.
I have read almost all questions on stackoverflow
undefined behaviour
pre/post inc.. dec.. operator precedence/associativity
use the parenthesis
but results are inconclusive.
please explain this i have an interview tomorrow.
int a, x = 0;
// value of x ------> a(sum)
//gcc 4.9.9.2[dev cpp] 2 1 2 4 5 14
//acc to my calculation 2 0 2 4 5 13
//geeksforgeeks compiler 5 5 5 5 5 15
//gcc 6.3 [codechef ide] 5 5 5 5 5 15
a = ((((++x + x++) + ++x) + ++x) + ++x);
printf("%d....%d", x, a);
return 0;
if i have made mistake please help me to correct them.
Thanks
There is no sequence point, thus your code invokes Undefined Behavior.
Parentheses do not introduce sequence points, thus, despite the fact that you use them, you still invoke UB.
This question already has answers here:
The need for parentheses in macros in C [duplicate]
(8 answers)
Closed 6 years ago.
I defined a function using #define, but when I print out a simple result of an operation it gives me an unexpected result. Here is the code:
#include <stdio.h>
#define CUBE(x) (x * x * x)
int main() {
int m, n = 3;
m = CUBE(n + 1);
printf("%d %d", m, n--);
return 0;
}
The result printed is 10 and 3 and I can't understand why. Since it multiplies n by itself 3 times, and then adds 1, shouldn't the result be 28 and 3?
You don't #define functions, you #define macros, and those are quite different from functions.
They aren't called. They are expanded into the source code directly by the preprocessor, before the code is compiled by the compiler.
They have pitfalls that one must be aware of. To name one, if you pass an expression with side effects to a macro the uses its parameter more than once, the side effects will occur more than once, and you may get wrong results.
The substation is plain token substitution, so
CUBE(n + 1)
will be expand to this:
(n + 1 * n + 1 * n + 1)
#define CUBE(x) ((x) * (x) * (x))
should give you the expected result.
In your, on preprocessing, x in CUBE(x) is replaced by 3+1 which gives you
(3+1 * 3+1 * 3+1) // this happens during pre-processing, not in run time
as macro is plain-text replacement.
which will be grouped like
(3+(1 * 3)+(1 * 3)+1)
giving you 10. For more complex cases, I suggest writing a function.
As the previous answer already suggest, you are missing a pair of brackets,
because the preprocessor basically does find and replace. So your version result in
m = n + 1 * n + 1 * n + 1
which evaluates to the result, you observed.
With
#define CUBE(x) ((x) * (x) * (x))
you will get the correct calculation of
m = (n + 1) * (n + 1) * (n + 1)
This question already has answers here:
Bitwise operation and usage
(17 answers)
Closed 6 years ago.
I'm writing a memory manager in C and am trying to make sure it's properly aligned (make sure the user space starts on an address divisible by 8, and make sure the whole block is divisible by 8 as well).
I was wondering if anyone could tell me what this does:
x = ((x - 1) | 7) + 1;
It's a code fragment that was suggested to me by a friend, but I'm unsure of what it's doing / what the vertical bar's function is in this scenario
Edit:
I realize I could've explained this a bit clearer; x is an int, and I did look up that it was a bitwise OR operator, but I didn't understand what that meant in this context. Thanks for the help!
A standard way to make a number divisible by 8 is:
len = (len + 7) & 0xfffffff8; /* for positive 32-bit values */
That should be easier to understand than your friend's construct (which BTW probably works as well, but see below).
The construct you have sets the lower 3 bits of your number by bitwise ORing it with 7 (thus creates a number that has a remainder of 7 when divided by 8), then adds 1 to make it divisible by 8. What the -1 means, you should work out on your own. I wouldn't even look at it nor use it if you don't anderstand what it does at first glance.
Whether it is advisable to use signed integers as addresses and block lengths you will surely get some other comments.
This statement is in an if statement, like so:
if (x % 8 != 0):
x = ((x - 1) | 7) + 1;
I should've just included more in the code fragment initially, apologies for that. Once I reviewed my binary math a little bit, I recognized that the "| 7" meant OR with 0111, and given that this is a statement used when x is thought to be misaligned, the results can only be as follows:
if (x-1) < 7 : ((x-1) | 7) is 0111. Adding 1 gives 8, which satisfies the condition.
if 15 > (x-1) > 7 : ((x-1) | 7) is 1111. Adding 1 gives 16, again satisfies
and so on for higher values.
Thanks for your suggestions everyone, this was my first question, I'll be sure to improve them in the future!