C Code Algebraic output is not what I thought - c

Please explain to me how th3 output is 11.
int main(){
int delta = 12, alpha = 5, a = 0;
a = delta - 6 + alpha++;
printf("%d", a);
return 0;
}

In C, putting ++ after a variable in an expression increments it after the expression is evaluated. Therefore, substituting the variables for their values, it would be a = 12 - 6 + 5, and afterwards alpha would be equal to 6.
If you put ++ before the variable, it increments it before the expression is evaluated. So therefore, if you had done a = delta - 6 + ++alpha, it would have been 12.

The result of x++ is the current value of x - as a side effect, x is incremented. Logically, your expression is equivalent to writing
tmp = alpha;
a = delta - 6 + tmp;
alpha = alpha + 1;
with the caveat that the assignment to a and the update to alpha can occur in any order, even simultaneously. Point is that a is computed with the value of alpha before the increment. Now, your specific compiler may choose to generate code like
a = delta - 6 + alpha;
alpha = alpha + 1;
because that makes sense here, but the point is that it isn't specified exactly when the side effect to alpha is applied.
The result of ++x is the current value of x plus one - as a side effect, x is incremented. Had you used ++alpha in your statement, it would logically equivalent to writing
tmp = alpha + 1;
a = delta - 6 + tmp;
alpha = alpha + 1;
with the same caveat as above. a is computed with the value of alpha + 1. Again, your compiler may choose to generate code equivalent to
alpha = alpha + 1;
a = delta - 6 + alpha;
or it could have done something like
a = delta - 6 + (alpha + 1);
alpha = alpha + 1;
Again, it isn't specified exactly when the side effect is applied.

Related

A problem with the most simple C operators

Can someone explain how this operation works?
#include <stdio.h>
int main()
{
int a = 5;
int b, c;
c = (a = 3) + (b = a + 2) - (a = 2);
printf("%d %d %d", a, b, c);
return 0;
}
The output is 2 5 5
Parentheses go first and start from the left.
c = 3 + (b = 3 + 2) - (a = 2)
c = 3 + 5 - 2
And the output should be 2 5 6
The 3 assignments in (a = 3) + (b = a + 2) - (a = 2) are a problem as it is undefined behavior as they are unsequenced: may occur in any order or even at the same time creating bus conflicts.
Best to re-write this poor code.
C doesn’t force left-to-right evaluation of arithmetic expressions - each of a = 3, b = a + 2, and a = 2 may be evaluated in any order (they are said to be unsequenced with respect to each other). Since two of those expressions modify the value of a, the result of b = a + 2 can vary based on the compiler, optimization settings, even the surrounding code - the result could be 7, 5, 2, or something else completely.
The behavior of modifying a multiple times and using it in a value computation without an intervening sequence point is undefined, meaning the compiler isn’t required to handle the situation in any particular way. It may give you the result you expect, but it doesn’t have to. The result doesn’t have to be consistent from build to build, or even from run to run.
This should give the results you would expect based on a left-to-right reading of your expression.
a = 3;
b = a + 2; // b = 5
c = a + b - 2; // c = 6
a = 2;

problem on performing increment in an expression

When i compile this code,it showing an error as lvalue required as increment operand
int main(void)
{
int x,y,z;
x=8++;
y=++x++;
z=(x+y)--;
printf("x=%d,y=%d,z=%d",x,y,z;
return 0;
}
When you write something++ or ++something it's roughly equivalent to
something = something + 1
(the difference between something++ and ++something is in what you get when you assign the result to something else).
Because of this, the operand of ++ has to be something you can assign to.
8++ is equivalent to 8 = 8 + 1, but you can't assign to a number.
++x++ would be equivalent to something like (x = x + 1) = (x = x + 1) + 1, I can't even fathom what this could be intended to mean.
(x+y)-- is equivalent to (x + y) = (x + y) - 1. You can't assign to an addition expression (which variable would you be setting)?
You should only use ++ or -- when you actually want to update a variable. It's not a general replacement for + 1 or - 1. So your program should be:
x = 8 + 1;
y = 1 + x + 1;
z = (x + y) - 1;
This will print
x = 9, y = 11, z = 19
constant cannot be changed. 8 is a constant value. (x+y) is also not the value which can be incremented and stored somewhere.
x++ uses the value of x then increments the x. So the lvalue is changed itself not only the result of the operation.
correct is
z=(x+y)-1;
x=8+1;

Why does increment operator modify the original value and bit operators don't?

The increment operator modifies the original value like,
int i = 5;
i++;
printf("%d",i); //prints 6
but the bit operator does not, example,
int x = 5;
x<<1;
printf("%d",x);//should print 10 but outputs the original value i.e. 5
x << 1 is analogous to operations like x * 2. If you don't store the result anywhere, it is just discarded and the line may just get omitted entirely by an optimizing compiler.
If you want to store the result of an operation like that back into x, you have options like:
x = x * 2;
x *= 2;
The << operator is the same:
x = x << 1;
x <<= 1;

Can't understand x *= y+1 output

I have a problem understanding the output of the code. Any explanation please...
#include<stdio.h>
void main()
{
int x=2,y=5;
x*=y+1;
printf("%d",x);
}
The output is as 12. But as per my understanding x*=y+1;is x=x*y+1; but as per operator precedence x*y should be evaluated followed by adding 1 so it should be 10+1=11. But it is 12 — can anyone explain please?
It will be evaluated as
x = x * (y + 1);
so
x = 2 * ( 5 + 1 )
x = 12
What's going on here is how the order of operations happens in programming.
Yes, if you were to have this equation x*y+1 it would be (x * y ) + 1 and result in eleven.
But in programming, the equation to the right of the = sign is solved for prior to being modified by the symbol proceeding the = sign. In this equation it is multiplied.
So x *= y + 1 is actually x = x * ( y + 1 ) which would be 12.
^ In this case, the asterisk(*) is multiplying the entire equation on the right hand side by x and then assigning that outcome to x.
It is translated into : x = x*(y+1);
So very obviously it prints out 12.
Your understanding is correct but it's somthing like this:
x*=y+1; => x = x * (y + 1);
Now apply BODMAS
x *= y + 1 is x = x * (y + 1)
Operator + has higher precedence than operator *=.
x*=y; works like x=x*y;
and here x*=(y+1) is getting expanded like x = x * (y + 1);
*= and similar ones are a type of C assignment operators, i.e. these operators are different from * and alike.
Now from C operator precedence, these operators have lowest precedence (higher than ,) hence y + 1 will be evaluated first, then *= will be evaluated and result will be assigned to x.
It evaluates as
x = x * (y + 1);
so
x = 2 * (5 + 1) = 12
Take a look at Operators order, you will see why in this case it is evaluated like that.
Here from operator procedure in c you can see
Addition/subtraction assignment has lower procedure than simply add operation.
so here
x*=y+1;
+ get executed first.
so
x = x * (6)
so x = 2 * 6
x = 12;

What is the difference between increment operator(++) and addition (+) operator?

What is the difference between increment operator ++ and an addition + operator? Why can't we can use + instead of ++?
What are the advantages of ++/-- operators over +/-? Where exactly are they applicable?
x++;
v.s.
x = x + 1;
The main advantage comes from pre-increment v.s. post increment:
e.g.
x = 1;
y = 1;
a = x + 1; // a is 2, x is 1 - e.g. does not modify x
a = ++x; // a is 1, x is 2
b = y++; // b is 2, y is 2
The major downside is that stuff like
a = ++x + x--;
is undefined behavior. Completely compiler dependent and WILL make life hell for anyone trying to figure out the "bug".
The only difference that is given by the C standard is the number of evaluations of x. For normal variables the difference usually doesn't matter. If the compiler can prove that in x = x + 1 the two evaluations of x should give the same value it might optimize this out.
If x is e.g declared volatile or involves the evaluation of a function, the evaluation must be done twice. Example:
unsigned* f(void);
then
*f() = *f() + 1;
is quite different from
++(*f());
The unary operators (++, --) are mainly there for convenience - it's easier to write x++ than it is to write x = x + 1 for example.
++ can also be used to do a 'pre-increment' or a 'post-increment'. If you write x++ then the value of x is increased and the original value of x is returned. For example:
int a = 0;
int x = 0;
a = x++; // x is now equal to 1, but a is equal to 0.
If you write ++x, x is still incremented, but the new value is returned:
int a = 0;
int x = 0;
a = ++x; // Both a and x now equal 1.
There is also usually a minor difference in the compiler's implementation as well. Post-increment (x++) will do something like this:
Create a temporary variable
Copy x to the temporary variable
Increment x
Return the temporary variable
Whereas pre-increment (++x) will do something like this:
Increment x
Return x
So using pre-increment requires less operations than post-increment, but in modern day systems this usually makes no worthwile difference to be a decent way of optimising code.
You could in fact use addition:
a = a + 1
But most people prefer the shorter version. In some languages it actually avoids the need to copy the value to a new location, but as nneonneo has helpfully pointed out, the C compiler is likely to optimise this for you.
"++" means "plus one"
eg
int x = 5;
x++; // the same as x = x + 1
cout << x; // will print 6
"+" is the known plus operator
++ is a convenience syntax. It does not really add capability to the language, but it adds a way of writing some common operations more concisely.
As a standalone statement a++; is identical to a+=1; is identical to a=a+1;
a++ can be useful in some situations that would otherwise need two statements:
while (a < N) doSomethingWith(a++);
is just a shorter form of
while (a<N)
{
doSomethingWith(a);
a=a+1;
}
I don't think there is anything you can write with an a++ that you couldn't also write with an a=a+1, but you can't just do a 1 for 1 substitution. Sometimes the 2nd form will require more code to be equivalent, since the 1st performs two things: produce the value of a, and then increment a. The a=a+1 form produces the value of a after the increment, so if you need the original value, you need a separate statement to process that first.
The difference between using the increment operator(ie. value++) vs using the addition operator(ie. value + 1) is that the first one sometimes can cause mutation especially if we are accessing a global variable inside a function;
Using increment operator.
// The global variable
var fixedValue = 4;
function incrementer () {
// Only change code below this line
return fixedValue ++;
// Only change code above this line
}
var newValue = incrementer(); // Should equal 5
console.log(fixedValue); // Should print 5
Using addition operator.
// The global variable
var fixedValue = 4;
function incrementer () {
// Only change code below this line
return fixedValue + 1;
// Only change code above this line
}
var newValue = incrementer(); // Should equal 5
console.log(fixedValue); // Should print 4
increment doing on register but addition do by ALU we can use + instead of increment but increment is faster

Resources