Questions on C expression - c

Here is a program:
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
a=12;
++a;
b=a++;
c=++a;
printf("a=%d,b=%d,c=%d",a,b,c);
getch();
}
The answers are a=15,b=13, c=15. But how?

x=++y means y is incremented before x receives the value of y.
x=y++ means y is incremented after x receives the value of y.
In the code:
The first ++a makes a = 13.
The line b=a++ makes b=a (13) and after that a = 14.
The line c=++a makes a = 15 and after that c = a (15).

The expression a++ evaluates to the current value of a; as a side effect, a is incremented. Thus, the expression
b = a++;
is equivalent to
b = a;
a = a + 1;
with the caveat that the exact timing of the updates to a and b with respect to each other isn’t specified. IOW, it’s possible that the current value of a is stored in a register, then a is incremented, then the value in the register is written to b. It’s possible that a and b are updated in parallel. All that’s guaranteed is that b gets the previous value of a.
The expression ++a evaluates to the current value of a + 1, and as a side effect increments a. Thus, the expression
c = ++a;
is equivalent to
c = a + 1;
a = a + 1;
with the same caveat as above.

++a means increment a, then use (in this case save).
a++ means use then increment

++a or a++ both work as a=a+1 but ++a first increases value of a by 1 and then assigns it to a. while a++ first assigns the value of a and then increments it by 1.
initially the value of a is declared as 12
statement '++a' first increases value of a by 1 and then assigns it to a. thus now, a=13
in statement b=a++, Value of a i.e. 13 is assigned to b and then it is incremented by 1. thus now, b=13 & a=14
in statement c=++a, value of a is incremented by 1 first and then it is assigned to c. thus c=15 & a=15.

Related

Evaluation order in ternary operator with increments

#define MAX(a,b) ((a)>(b) ? (a) : (b))
int main(void) {
int a=2;
int b=3;
int c = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
printf("\na= %d", a);// a=3
printf("\nb= %d", b);//b=5
printf("\nc= %d", c);//c=4
a=3;
b=2;
cc = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
printf("\na= %d", a); // a=5
printf("\nb= %d", b); //b=3
printf("\nc= %d", c); //c=4
return 0;
}
I would like to know why c is not evaluating to 5.
It appears to me the evaluation order should be:
First both a and be get incremented in (a++)>(b++)
If for example the first one is greater, the ternary operator in
c=((a++)>(b++) ? (a++) : (b++)), goes to (a++), so a
increments again.
The result of the ternary expression, which is a twice-increment,
should be assigned to c, then c should have the greater value
twice-incremented, that is 5. However, I am getting 4. I suspect the
greater value's second increment is happening at the end, but I can't
explain why, since the parentheses seem to indicate that the
assignment comes at the end.
Any idea?
The postfix ++ operator has a result and a side effect. The result of a++ is the value of a before the increment - given
int a = 1;
int x = a++;
the value of x will be 1 and the value of a will be 2. Note that the side effect of adding 1 to a does not have to be applied immediately after evaluation - it only has to be applied before the next sequence point.
So, looking at
((a++) > (b++)) ? (a++) : (b++)
The ?: operator forces left-to-right evaluation, so the first thing that happens is that (a++) > (b++) is evaluated1. Since a is initially 2 and b is initially 3, the result of the expression is false (0). The ? operator introduces a sequence point, so the side effects to a and b are applied and a is now 3 and b is now 4.
Since the result of the condition expression was 0, we evaluate b++. Same thing, the result of the expression is the current value of b (4), and that value gets assigned to c. The side effect to b is applied at some point, and by the time everything's finished, a is 3, b is 5, and c is 4.
Although within that expression either a++ or b++ may be evaluated first, since the > operator doesn't force left-to-right evaluation.
Let's consider for example this declaration
int c = MAX(a++,b++);
after the macro substitution there will be
int c = (( a++) >( b++ ) ? (a++) : (b++));
The variables a and b are initialized like
int a=2;
int b=3;
As a is less than b then the third expression (b++) will be evaluated as a result of the conditional operator. In the first expression ( a++) >( b++ ) a and b were incremented. There is a sequence point after the evaluation of the first expression.
So a will be set to 3, b will be set to 4.
As it was already said the value of the conditional operator is the value of the third expression (b++) where there is used the post-increment. The value of the post-increment operator is the value of its operand before incrementing.
From the C Standard (6.5.2.4 Postfix increment and decrement operators)
2 The result of the postfix ++ operator is the value of the
operand. As a side effect, the value of the operand object is
incremented (that is, the value 1 of the appropriate type is added to
it).
So the value of the conditional operator is 4. This value will be assigned to the variable c. But as a side effect the value of b will be incremented.
Thus after this declaration a will be equal to 3, b will be equal to 5 and c will be equal to 4.
For clarity this declaration
int c = (( a++) >( b++ ) ? (a++) : (b++));
in fact can be rewritten in the logically equivalent way.
int result = a > b;
++a;
++b;
int c;
if ( result != 0 )
{
c = a++;
}
else
{
c = b++;
}
For a++ it's equivalent as saying
int temp = a;
a = a + 1;
return temp;
so in the case of a=2, b=3, we can go to the condition (a++)>(b++) and we can have a rewritten as
int temp1 = a;
a = a + 1;
return temp1;
and b rewritten as
int temp2 = b;
b = b + 1;
return temp2;
now since it's only a conditional statement, we're really just evaluating the old values of a and b before the increment which is temp1 = 2 and temp2 = 3 while at the same time a and b values have changed a = 3, b = 4. Since temp1 < temp2 from the old value, we go to the false clause of the ternary operator (b++) and do the same thing as we did before
int temp3 = b;
b = b + 1;
return temp3;
so now b is 5 while the returned temp3 is the previous value of b which is 4. Hope this helps!

differences in C: *source++, (*source)++, *(source)++

IS there a difference between these pointers? What exactly is happening here for each call.
*p++
(*p)++,
*(p)++
1 and 3 are the same.
Remember that both postfix and unary forms of ++ and -- have a result and a side effect:
The result of x++ is the current value of x - as a side effect, x is incremented by 1 (if x is a pointer, it is incremented to point to the next object in a sequence);
The result of ++x is the current value of x plus 1 - as a side effect, x is incremented by 1 (if x is a pointer, the result is the address of the next object in a sequence, and x is updated to point to the next object in a sequence);
Both forms of -- work the same way, except the value is decremented by 1 - if it's a pointer, then it's set to point to the previous object in a sequence.
When you throw pointer dereferences into the mix, you get the following:
The expression *p++ is parsed as *(p++) (so is *(p)++). The result of *p++ is the current value of *p (the value of the thing p is currently pointing to). As a side effect, p is incremented to point to the next object of the same type in a sequence (IOW, the next element of an array);
The expression (*p)++ is parsed as written. The result of (*p)++ is the current value of *p. As a side effect, *p is incremented by 1. That is, the value of the thing being pointed to is updated, not the pointer.
The expression ++*p is parsed as ++(*p). The result of ++*p is the current value of *p plus 1. As a side effect, *p is incremented by 1.
The expression *++p is parsed as *(++p). The result of *++p is the value of the object following the object p currently points to. As a side effect, p is incremented to point to the next object.
Assume the following declarations:
int a[] = {1, 2, 3, 4};
int *p = a;
After these lines, the value of p is &a[0]. So, given the expression
x = *p++;
the result of *p++ is 1 (the value of the thing p currently points to), which gets assigned to x. The side effect is that p is updated to point to a[1].
Then we execute
x = (*p)++;
The result of (*p)++ is the value of the thing p currently points to (if p points to a[1], then the value is 2), which gets assigned to x. As a side effect, the thing p points to is incremented (if p points to a[1], then the value of a[1] is now 3).
The we execute
x = ++*p;
The result of ++*p is the value of the thing p points to plus 1, and as a result the thing p points to is incremented (if p points to a[1], then the value of a[1] + 1 is 4, which is assigned to x, and the value of a[1] is now 4).
Finally, we execute
x = *++p;
The result of *++p is the value of the object following the object that p currently points to, and p is incremented to point to that object (if p points to a[1], then the value of a[2] (3) is written to x, and p is updated to point to a[2]).
Again, -- works the same way, just in the other direction.
tiny test program.
#include <stdio.h>
int main(void) {
char z[] = "World";
char n[] = "Something";
char *x = "Hello!!";
while(*x) printf("%c", *x++);
printf("\n");
x = z;
while(*x) printf("%c", (*x)++);
printf("\n");
x = n;
while(*x) printf("%c", *(x)++);
printf("\n");
return 0;
}
so the *x++ dereference the pointer, then increments the pointer
(*x)++ - only increments the referenced object.
*(x)++ == *x++
IMO instead of asking try yourself. You will learn something https://ideone.com/bliza0
*source++ will be parsed as *(source++) because of higher precedence of ++ over * operator. It will increment the pointer by 1 and then will dereference the pointer.
To understand the behaviour first let me explain how post increment operator works. When you do
int i = 0;
int j = i++;
then it means that the value of the expression i++ will be the value of the operand i. In this case it will be 0. The value of the i will be incremented as a side-effect. See the quote from the draft
n1570 - §6.5.2.4/2:
The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The value computation of the result is sequenced before the side effect of updating the stored value of the operand.
In case of *source++, compiler will parse it as *(source++). The result of the expression source++ is the value of source. So the current pointer (the address source is pointing to before the side-effect) will be dereferenced and then the side-effect on source will be performed.
(*source)++ will first dereference the pointer and then increment the dereferenced value by 1.
*(source)++ is equivalent to the first case.
I apologies for the wrong answer and leaving the wrong answer with strikes so that future readers will take a lesson if any one come to the same wrong conclusion as I did. Thanks #interjay and #pmg for correcting me out. I am really glad that you guys are part of this community and contributing to this community with your sharp eyes and mind.

In C, is a+++b equal to a+b++? [duplicate]

This question already has answers here:
Why doesn't a+++++b work?
(9 answers)
Closed 5 years ago.
In C, is a+++b equal to a+b++?
They are and will be equal if you supply the same initial values of the operands.
In your case, the side effect of the first statement (post increment on a) is affecting the second one. Due to the presence of the post-increment in the first expression, a is incremented to 3 before the next statement is executed.
Re-initialize the variables with the same genesis value before calculating the second one.
You need to check the C operator precedence to understand it.
The confusing thing here is that a+++b may be read as either a + (++b) or as (a++) + b. According to the C operator precedence, it is actually looks like:
int a=2, b=3, c;
c = (a++) + b; // 2+3=5 and 'a' will be 3 after that line
printf("%d\n",c); // c = 5
c = a + (b++); // 3+3=6 and 'b' will be 4 after that line
printf("%d\n",c); // c= 6
From the link above:
++ as sufix has highest priority.
++ as prefix has lower priority.
+ has even lower priority.
int a=2, b=3, c;
c = (a++) + b; // The value for a will be 3 after that line
printf("%d\n",c); // c = 5
c = a + (b++); // So here a value is 3 (3+3) =6 after executing this line b value will be 4
printf("%d\n",c); // c= 6
To avoid this you need to reinitialize the variables
c = a+++b;
is equivalent
c = a++ + b;
a++ means post-increment, means expression takes the value of a and then increment.
c = a+b++;
is equivalent
c = a + b++;
b++ means post-increment, means expression takes the value of b and then increment.
If you provide same value in both cases, then both express variable c same.

C language basics 1

What is the difference between a++ and a=a+1 in C if a is a variable.
Tell me the difference between the following assignments;
x=a+1;
x=a++;
I am not able to find a convincing explanation on Google.Please explain the difference clearly and step by step.
a = a+1; calculates the result of a+1 and assigns it to a.
a++; increments a by 1, but evaluates to the previous value of a.
++a; increments a by 1, and evaluates to the new value of a.
a += 1 is identical to ++a;.
So for example:
x = a++; → a will be incremented by 1, and the previous value of a will be assigned to x.
x = ++a; → a will be incremented by 1, and the new value of a will be assigned to x.
x=a+1 just sets the value of x.
x=a++ first sets x to the value of a, and then increments a. a++ is an operation in itself, and you could call it as a single statement to increment a, without assigning it to x whatsoever.
FYI, there is also ++a, which could be used like this:
x=++a. In this case, a is incremented first, and then the incremented value is assigned to x. In either case, the ++ operator modifies a, which is not the case for a+1.
From the C11 Standard (draft):
6.5.2.4 Postfix increment [...] operator[...]
[...]
2 The result of the postfix ++ operator is the value of the operand. As a side effect, the
value of the operand object is incremented (that is, the value 1 of the appropriate type is
added to it).
So
int a = 0;
int x = a++;
results in a being 1 and x being 0.
x = a++ returns the value of a to the variable x first and later it is incremented.
x = a+1 Here a+1 is evaluated and the result is stored in x
3 differences
Return value and side effect
// a is incremented, but its former value is assigned to x
x=a++; //
// a is unchanged. The sum of `a+1`is assigned to x
x=a+1;
Operator precedence. post-fix ++ (aka Suffix increment) is higher precedence than simple addition.
++ only works with integer and non-void* pointer types. +1 works with all scalar type including double.
int a;
x=a++; // valid
x=a+1; // valid
double a;
x=a++; // invalid
x=a+1; // valid

pre/post increment pointer

Is there a difference between the two expressions:
(*x)++
and
++(*x)
I can see both of these statements replace the contents of (*x+1) in *x. But are there any differences between them?
(*x)++ evaluates to the value of*x; as a side effect, the value in *x will be incremented by 1.
++(*x) evaluates to the value of *x + 1; as a side effect, the value in *x will be incremented by 1.
Assuming the code:
int a = 5;
int *x = &a;
(*x)++ will evaluate to 5, while ++(*x) will evaluate to 6.
Note that the side effect does not have to be applied immediately after the expression has been evaluated; it only needs to be applied before the next sequence point.
Also note that the parentheses matter for (*x)++; postfix ++ has higher precedence than unary *, so *x++ would be parsed as *(x++); it still evaluates to the value of *x, but as a side effect advances the pointer, rather than increment the thing being pointed to. Prefix ++ and unary * have the same precedence, so they're applied left-to-right; thus ++(*x) and ++*x would have the same result (*x gets incremented, not x).
Let us say the value pointed by x is 10 i:e (*x is 10)
y = (*x)++;
the above statement will be executed as
1. y = *x
2. *x = *x + 1
so y = 10 & *x is 11
y = ++(*x);
the above statement will be executed as
1. *x = *x + 1
2. y = *x
so y = 11 & *x is 11
One increments the values stored in x before it is used (pre), while the other does it after it is used (post).
Also note that ++(*x) is not the same as (*x + 1). The first increments the value and stores it back, the other just increments the value.
One is "pre" and the other is "post". That's the difference. One is evaluated before the the increment (the first option), the other is evaluated after the increment (the second option).

Resources