#define ADD1(a,b)(a+b)
#define ADD2(a,b)(a + b)
x=5,y=2
z1=ADD1(x.++y);
printf("%d %d %d",x,y,z1);
x=5,y=2
z2=ADD2(x,++y);
printf("%d %d %d",x,y,z2);
The answer is
x=6,y=2,z1=7
x=5.y=3,z=8
`I thought the output in both is x=5,y=3,z1/z2=8
why theres a difference between them?```
The problem is that ADD1 results in x+++y. That is evaluated as x++ + y, and not x + ++y as you had expected. Note that, in that computation, x++ does not have any effect on the result, because x is incremented after the addition.
See a demonstration here: https://onlinegdb.com/EvqOw8s87
You should use parentheses in your definitions, to avoid such ambiguities:
#define ADD1(a,b)((a)+(b))
#define ADD2(a,b)((a) + (b))
This makes them behave the same
Related
#include <stdio.h>
#define foo(x,y) x/y +x
int main()
{
int i=-6,j=3;
printf("%d",foo(i+j,3));
}
PROBLEM;
this code is giving answering -8
is not it return -4 mathematically ..
please explain ..help
foo(x,y) is defined as x/y +x, so foo(i+j,3) expands to i+j/3 +i+j. Since / has higher precedence than +, this is equivalent to i + (j / 3) + i + j, not to (i + j) / 3 + i + j as you presumably intended.
The best fix in this case is to not use a macro, but rather, to just write a normal function:
int foo(int x, int y) {
return x / y + x;
}
If, for whatever reason, that's not an option, then you need to add some parentheses:
#define foo(x,y) ((x) / (y) + (x))
. . . but even this will give weird results if the x has side-effects, because the x gets expanded twice, so those side-effects will happen twice. (And in some cases that will result in undefined behavior.)
It's -8 of the way macros work in C. At compile time, all macros in your code are replaced verbatim with the macro definition.
So, in your example, all occurrences of foo(x+y) are replaced with x/y +x which when applied to the printf goes from
printf("%d",foo(i+j,3));
to
printf("%d",i+j/3 + i+j);
which, when substituted with the values of i and j give the following
printf("%d",-6+3/3 + -6+3);
And thus, -8 is printed.
This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 5 years ago.
I've found this question somewhere and couldn't understand it. Please help me out with this.
#include<stdio.h>
int main(){
char x = 250;
int ans = x + !x + ~x + ++x;
printf("%d", ans);
}
The output comes out to be -6. I don't understand how the compiler performs operation.
Thanks in advance!
When you're trying to understand something like this, it's often helpful to break the problem down into smaller pieces and look at each one. I modified your program so that it prints each of the values:
#include<stdio.h>
int main(){
char x = 250;
printf("x: %d\n", x);
printf("!x: %d\n", !x);
printf("~x: %d\n", ~x);
printf("++x: %d\n", ++x);
int ans = x + !x + ~x + ++x;
printf("ans: %d\n", ans);
}
And the output I get when I run it is:
x: -6
!x: 0
~x: 5
++x: -5
ans: -5
Once you understand what each part means, it's easier to see how they combine into the final result. However, my compiler also emits a warning because ++x modifies x in the same expression that uses x in other places, and changing the order in which the terms are evaluated will change the final result.
This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 6 years ago.
Please explain me the outcome of this code.
//code a
when I run this code on my laptop, value of y is 4. And I think, logically value of y should be 5 because by doing x++ it should return 2 without incrementing as it is post increment and then when we add x which now contains an incremented value ie 3. So 2+3 is 5, according to me. But according to my turbo c++ 3.0 answer is 4.
#include <stdio.h>
void main() {
int x = 2,y;
**int y = x++ + x;** // ans 4
printf("y is :%d", y);
}
// code B
When I run this code, the answer is 6. Here turbo c++ 3.0 in ++x is picking up an incremented value of x++, which is the opposite of above mention code. Logically here answer is correct but in the above code it's not.
#include <stdio.h>
void main() {
int x = 2,y;
**int y = x++ + ++x;** //and 6
printf("y is :%d", y);
}
Firstly, assignment operator that is = works from right to left, which means if you write x = 2 + 4 + 1; your compiler starts reading it from rightmost digit that is 1 then it add 4 to it and so on and then it assigns that value to x.
So, in your case statement y = x++ + x; compiler starts seeing it from right that is it first sees x i.e. 2 and then sees x++ i.e. also 2 as it is post increment operator finally it adds them and assigns y as 2 + 2 that is 4.
In the second case, that is y = x++ + ++x;, compiler first looks at ++x and as it is pre increment operator it increases x with one, i.e. x is now 3. After that x++ is seen and as stated above because it is post operator it would be treated as x in this operation and that value is 3 (remember we incremented x by one earlier) and hence, compiler assigns 3 + 3 i.e. 6 to y.
First program where the result is 4
#include <stdio.h>
void main() {
int x = 2,y;
**int y = x++ + x; // x=2, so y=2+2=4
printf("y is :%d", y); // after post increment x=3
}
Since a variable only gets it post incremented value only after the execution of the statement is completed so y=2+2
Second program where the result is 6.
Associativity of ++ operator is "right to left"
void main() {
int x = 2,y;
**int y = x++ + ++x; //Since associativity is left to right so y=3+3=6
printf("y is :%d", y);// after the post increment x=4
}
Here the pre-increment is performed first since because of the associativity rule so y=3+3
I came across a statement in the text C How to Program:
"Expressions with side effects (i.e., variable values are modified) should not be passed to a macro because macro arguments may be evaluated more than once.".
My question is what are expressions with side effects and why should they be not passed to a macro?
The classic example is a macro to calculate the maximum of two value:
#define MAX(a, b) ((a) > (b) ? (a) : (b))
Now lets "call" the macro like this:
int x = 5;
int y = 7;
int z = MAX(x++, y++);
Now if MAX was a normal function, we would expect that x and y would be incremented once, right? However because it's a macro the "call" is replaced like this:
int z = ((x++) > (y++) ? (x++) : (y++));
As you see, the variable y will be incremented twice, once in the condition and once as the end-result of the ternary operator.
This is the result of an expression with side-effects (the post-increment expression) and a macro expansion.
On a related note, there are also other dangers with macros. For example lets take this simple macro:
#define MUL_BY_TWO(x) (x * 2)
Looks simple right? But now what if we use it like this:
int result = MUL_BY_TWO(a + b);
That will expand like
int result = (a + b * 2);
And as you hopefully knows multiplication have higher precedence than addition, so the expression a + b * 2 is equivalent to a + (b * 2), probably not what was intended by the macro writer. That is why arguments to macros should be put inside their own parentheses:
#define MUL_BY_TWO(x) ((x) * 2)
Then the expansion will be
int result = ((a + b) * 2);
which is probably correct.
To put it simply a side effect is a write to an object or a read of a volatile object.
So an example of a side effect:
i++;
Here is a use of a side effect in a macro:
#define MAX(a, b) ((a) > (b)) ? (a) : (b))
int a = 42;
int b = 1;
int c;
c = MAX(a, b++);
The danger is contrary to a function where the arguments are passed by value you are potentially modifying b object one or two times (depending on the macro arguments, here one time) in the macro because of the way macros work (by replacing the b++ tokens in the macro definition).
Side Effects can be defined as:
Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).
For example:
int x = y++; //where y is also an int
In addition to the initialization operation the value of y gets changed due to the side effect of ++ operator.
Now consider a macro for squaring of an integers :
#define Sq(a) a*a
main()
{
int a=6;
int res=Sq(a);
printf("%d\n",res);
res=Sq(++a);
printf("%d",res);
}
You would expect the output to be
36
49
However the output is
36
64
because macro results in textual replacement and
res becomes (++a)*(++a)
i.e, 8*8=64
Therefore we should not pass arguments with side effects to macros.
(http://ideone.com/mMPQLP)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on that code, and I tried to use x + 1 instead of ++x and the result was infinite loop and zeros were printed on the screen.
this is the code:
#include <stdio.h>
int main(void){
int x;
for(x = 0; x <= 100; x + 1) //instead of ++x
printf("%d\t",x);
return 0;
}
I wondered this action.....why the compiler didn't produce such an error,,,, and what actually happens??!! and is x++ is treated as x += 1 ?!
You need the value of x to change, or your loop will never terminate. When you have only x + 1, then at the end of the iteration, x + 1 is computed, but its resulting value is discarded. The result of the expression is not stored any place. So x will remain zero, and x <= 100 will remain true, and your loop will continue forever.
If you have any of the following:
x = x + 1
x += 1
x++
++x
the value of x itself is incremented. That's what you need.
Although the basic structure of a for loop is like-
for(initialization; condition; increment or decrement)
But in its core part the "condition" part is treated only to control the loop behavior. So, if other two parts are syntactically correct, then compiler won't produce any error.
Since, x+1 is a valid C statement and the value of the x is not changing so it will go to an infinite loop for the condition [x <= 100 => 0 <= 100] being true forever.
Again, x++ or ++x both treated as x = x + 1 when used independently. But, x++ is actually Post-increment operator, while ++x is Pre-increment operator. That means, the with ++x, the value of the x will be incremented first and then assigned to x. Whereas, the current value of x will be used for the entire statement in x++ and then x will be incremented and assigned with new value. Look at the following example-
#include<stdio.h>
void main()
{
int x=5;
/* Post & Pre-Increment used independently */
x++;
printf("x : %d", x);
++x;
printf("\nx : %d", x);
/* Used with printf() statement */
printf("\nPre-increment of x: %d", ++x);
printf("\nPost-increment of x: %d", x++);
printf("\nPost-increment effect on x: %d", x);
}
Output:
x : 6
x : 7
Pre-increment of x: 8
Post-increment of x: 8
Post-increment effect on x: 9
I Hope my explanation have made you understand, if still not you can reply me back.
The expression x + 1 should be x = x + 1 in for loop, so correct:
for(x = 0; x <= 100; x + 1)
^
doesn't increment x
Infinite loop!
as:
for(x = 0; x <= 100; x = x + 1)
or
for(x = 0; x <= 100; x += 1) // or simply x++ or ++x
The compiler didn't produce such an error because x + 1 is a valid expression (but its not what you wants).
So, x += 1, x++ or ++x are not just add one to x but also modify value of x.
Your approach is not perfect because it definitely increases the value of x but when it comes to assignment, it fails. so your statements should cover all your requirements.
try to use
#include <stdio.h>
int main(void){
int x;
for(x = 0; x <= 100; x = x + 1)
printf("%d\t",x);
return 0;
}
or you can use
#include <stdio.h>
int main(void){
int x;
for(x = 0; x <= 100; x++)
printf("%d\t",x);
return 0;
}
Instead of x++ (post increment) you can also use pre increment (++x).
The expression x = x + 1; can also be written as x += 1; which is a shorthand method for assignment embedded with increment. It is not just about incremnent you can also use other operators.
x -= 3;
x *= 2;