Garbage value with post increment - c

Question 1
int x;
if (x++)
{
printf ("\nASCII value of X is smaller than that of x");
}
Is x assigned here with a garbage value ??
Question 2:
main ()
{
int i;
for (i = 0; i++ < 10;)
{
printf ("%d\n", i);
}
}
Can anyone explain how i++ < 10 works?I mean it should end at 9 why 10

The value of x is indeterminate, and is possibly a trap representation, in which case the behavior of x++ is undefined.
The expression i++ evaluates to the current value of i; as a side effect, the value in i is incremented. So if i == 1, the expression i++ will evaluate to 1, and as a side effect i will be set to 2.
Chapter and verse:
6.5.2.4 Postfix increment and decrement operators
...
2 The result of the postfix ++ operator is the value of the operand. After the result is
obtained, the value of the operand 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 side effect of updating the stored value of the operand shall occur between
the previous and the next sequence point.
Emphasis mine.

In the first question, you declare x
int x;
but you do not assign it, this reserves some memory to hold the value of x, but doesn't initialize it to a known value. That's a really bad thing. Then you read it, increment it, and possibly do something.
if ( x++ ) {
printf ( "\nascii value of X is smaller than that of x" ) ;
}
Since you don't know what it's value was before you read it, it is impossible to make an educated guess as to whether your if statement will print anything.
In your second question (please one question per question), you read the value of i, then increment it, and then do the comparison on the read value. Post increment basically means, "increment the value after I read it" and so the new value will be stored, then the comparison made on the old value, and the printf statement below will print the "current, new" value.

Question 1: Yes
Question 2: Yes. i is incremented by one then compared if it's lesser than 10.

Related

Is formatted output equivalent? [duplicate]

This question already has answers here:
What is the difference between prefix and postfix operators?
(13 answers)
Closed 11 months ago.
When I was doing the practice questions today, I found that the outputs of printf("%d\n",x--); and printf("%d\n",x); are the same.
I changed it to printf("%d\n",x++); and found to be the same. I want to know why.
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x);
if (x++ > 5)
printf("%d",x);
else
printf("%d\n",x--);
return 0;
}
You used the post-decrement/-increment operators.
x-- decrements x and returns the original value of x.
x++ increments x and returns the original value of x.
To get the desired behaviour, use the pre-decrement/-increment operators.
--x decrements x and returns the modified x.
++x increments x and returns the modified x.
That's simple and you can understand as well if you know the usage of these 2 kind of operators.
Post Increment/Decrement Operator e.g. a++, a-- etc.
So when we use it in the statement, the current value of the variable will be used and post that its value is incremented by 1.
Just take a look into my comments at end of statements (shows the o/p).
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x); // 10
printf("%d", x++); // 10
printf("%d", x); // 11
return 0;
}
Pre Increment/Decrement Operator, e.g. ++a, --a etc.
So when we use it in the statement, first its value of variable is incremented by 1 & then the incremented value will be used.
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x); // 10
printf("%d", ++x); // 11
printf("%d", x); // 11
return 0;
}
I think, now it's clear to you. For info on usages, just take a look into Usage of Pre/Post Increment & Decrement operators in C.
According to 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)
and
3 The postfix -- operator is analogous to the postfix ++ operator,
except that the value of the operand is decremented (that is, the
value 1 of the appropriate type is subtracted from it).
Consider this pair of calls of printf
int x = 10;
printf( "%d\n", x++ );
printf( "%d\n", x );
The output is
10
11
That is the value of the expression of x++ is the value of its operand that is equal to 10. As a side effect the variable x is increased and in the second call of printf the new value of x after applying the side effect is outputted.
You can imagine this call
printf( "%d\n", x++ );
like
printf( "%d\n", x ), x += 1;
Opposite to postfix increment and decrement operators the values of unary increment (++x) and decrement (--x) operators are values after incrementing and decrementing their operands.
From the C Standard (6.5.3.1 Prefix increment and decrement operators)
2 The value of the operand of the prefix ++ operator is incremented.
The result is the new value of the operand after incrementation.
and
3 The prefix -- operator is analogous to the prefix ++ operator,
except that the value of the operand is decremented.

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

Strange behavior from a simple C program

If I run the following code, graph[0][0] gets 1 while graph[0][1] gets 4.
In other words, the line graph[0][++graph[0][0]] = 4; puts 1 into graph[0][0] and 4 into graph[0][1].
I would really appreciate if anyone can offer reasonable explanation.
I observed this from Visual C++ 2015 as well as an Android C compiler (CppDriod).
static int graph[10][10];
void main(void)
{
graph[0][++graph[0][0]] = 4;
}
Let's break it down:
++graph[0][0]
This pre-increments the value at graph[0][0], which means that now graph[0][0] = 1, and then the value of the expression is 1 (because that is the final value of graph[0][0]).
Then,
graph[0][/*previous expression = 1*/] = 4;
So basically, graph[0][1] = 4;
That's it! Now graph[0][0] = 1 and graph[0][1] = 4.
First let's see what is the unary (prefix) increment operator does.
The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation.
So, in case of
graph[0][++graph[0][0]] = 4;
first, the value of graph[0][0] is incremented by 1, and then the value is used in indexing.
Now, graph being a static global variable, due to implicit initialization, all the members in the array are initialized to 0 by default. So, ++graph[0][0] increments the value of graph[0][0] to 1 and returns the value of 1.
Then, the simpllified version of the instrucion looks like
graph[0][1] = 4;
Thus, you get
graph[0][0] as 1
graph[0][1] as 4.
Also, FWIW, the recommended signature of main() is int main(void).
You are adding one to graph[0][0], by doing ++graph[0][0]. And then setting graph[0][1] to 4. Maybe you want to do graph[0][graph[0][0]+1] = 4
At first your variable graph[10][10] is static so it will be initialized with value 0.
Then line graph[0][++graph[0][0]] = 4 ; here graph[0][0] = 0 in expression you just incrementing the value of graph[0][0] so basically you assigning graph[0][1] = 4; yourself
Note that you have used pre-increment operator (++x) so it first get incremented and value is changed but if you would have use post-increment operator(x++) then graph[0][0] = 4; itself
Let's line up the facts about this expression
graph[0][++graph[0][0]] = 4;
Per 6.5.1, the computation of the array index ++graph[0][0] is sequenced before the computation of array element graph[0][++graph[0][0]], which in turn is sequenced before the computation of the entire assignment operator.
The value of ++graph[0][0] is required to be 1. Note that this does not mean that the whole pre-increment together with its side-effects has to "happen first". It simply means that the result of that pre-increment (which is 1) has to be computed first. The actual modification of graph[0][0] (i.e. changing of graph[0][0] from 0 to 1) might happen much much later. Nobody knows when it will happen exactly (sometime before the end of the statement).
This means that the element being modified by the assignment operator is graph[0][1]. This is where that 4 should go to. Assignment of 4 to graph[0][1] is also a side-effect of = operator, which will happen sometime before the end of the statement.
Note, that in this case we could conclusively establish that ++ modifies graph[0][0], while = modifies graph[0][1]. We have two unsequenced side-effects (which is dangerous), but they act on two different objects (which makes them safe). This is exactly what saves us from undefined behavior in this case.
However, this is dependent on the initial value of graph array. If you try this
graph[0][0] = -1;
graph[0][++graph[0][0]] = 4;
the behavior will immediately become undefined, even though the expression itself looks the same. In this case the side-effect of ++ and the side-effect of = are applied to the same array element graph[0][0]. The side-effects are not sequenced with relation to each other, which means that the behavior is undefined.

Why is the -- operator not subtracting from the value when executed? [duplicate]

This question already has answers here:
What is the difference between prefix and postfix operators?
(13 answers)
Closed 8 years ago.
Why is the decrement operator -- not bringing the value down by 1 when executed?
int a = 20;
int c ;
c = a--;
Inspecting the value of c now, it should be 19, yet it comes out as 20. What am I missing?
a-- is Post-Decrement, what you need --a Pre-Decrement. Please read Increment and decrement operators on Wiki
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int x;
int y;
// Increment operators
x = 1;
y = ++x;
// x is now 2, y is also 2
y = x++;
// x is now 3, y is 2
// Decrement operators
x = 3;
y = x--;
// x is now 2, y is 3
y = --x;
// x is now 1, y is also 1
what you're using is called a postfix operator. It will get executed [decrement the value] after the assignment = operator has finished its execution with the existing value.
To be clear, in case of post decrement, the ..-- operator is evaluated and the decrement is scheduled once the other evaluations including that operand are finished. It means, the existing value of the operand is used in the other evaluation [in =] and then the value is decreased.
If you want, try printing the value of a itself. It will print the decremented value.
EDIT:
If my choice of words in my answer created any confusions, for the reference, from the c99 standard, chapter 6.5.2.4, [emphasis mine]
[For increment] The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented [......]
The postfix -- operator is analogous to the postfix ++ operator, except that the value of the operand is decremented (that is, the value 1 of the appropriate type is subtracted from it).
You are using the post decrement. Post decrement means first use the value in a variable or
anything then decrement the value in the variable. So in this case first value of a will assigned to c. And the decrement is done. You can check printing the value of a.
you should use --a (pre decrement operator), you are using post decrement operator a--
The result of the postfix -- operator is the value of the operand. As a side effect, the
value of the operand object is decremented (that is, the value 1 of the appropriate type is
subtracted to it).

understand complex expression in C [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 6 years ago.
Help me please understand the following expression:
(seen in a book)
*((int *)marks + i++) = i+1
A large number of increments and symbols dereference confusing!
I hope the book had this as a bad example, because the behavior of that is undefined.
(int *)marks interprets marks (whatever that may be) as a pointer to int, then we have the result of i++ added to that. This pointer is dereferenced and i+1 is assigned to the corresponding object.
This expression has no defined behavior because it reads and modifies i at two different subexpressions that are not sequenced one before the other.
Burn the book.
The behaviour of the statement is undefined due to there being no sequence points. A far simpler case to understand is i++ = i which is also undefined.
Note: As others have said, the i++ expression is undefined behavior. In g++, the i++ operation will be executed as follows:
// Pointer to some data.
void* marks = ???;
// Typecast to an integer pointer
int* marksIntPointer = (int*)marks;
// Move the position in memory. I am assuming that 'marks' is an array.
int* marksIntPointerOffset = marksIntPointer + i;
// Undefined behaviour, could take place here or before, depending on the compiler (as others have said).
i++;
// Set the value of the desired memory.
*marksIntPointerOffset = i+1;
The mentioned expression yields an undefined behavior.
C99 6.5 §2 states:
1) Between the previous and next sequence point an object shall have its stored value
modified at most once by the evaluation of an expression.
2) Furthermore, the prior value shall be read only to determine the value to be stored.
1) Storing and modifying the value of variable within a single expression is pretty straightforward:
i = ++i;
i++ = i;
++i = 7;
as well as modifying the value of the same variable multiple times within a single expression:
j = ++i + ++i;
2) Reading only to determine the value to be stored might be a bit tricky though. This means that even the following (just like the previous examples) invoke the undefined behavior:
j = (i + 1) + i++;
a[i++] = i;
*(ptr + i++) = i;
as well as:
*((int *)marks + i++) = i+1
You might look at: Undefined behavior and sequence points as well :)
As others have mentioned, the behavior is undefined; by getting rid of the ++ operator, the following code would be well-defined (but still ugly as sin):
*((int *)marks + i) = i+1
Here's how it breaks down:
marks -- take the expression marks
(int *)marks -- cast it as a pointer to int
(int *)marks + i -- offset i integer elements from that address
*((int *)marks + i) -- deference the result to get an array element
*((int *)marks + i) = i+1 -- assign the result of i+1 to that element
This is essentially treating marks as an array of int, and assigning the result of i+1 to the i'th element:
int *mp = (int *) marks;
mp[i] = i+1
The original expression was trying to do
mp[i++] = i+1
which invokes undefined behavior. Since the order in which i++ and i+1 are evaluated is not specified; the compiler is free to evaluate them in any order it feels like. Since i++ has a side effect (updating the value of i), this means that you will get different results based on the platform, optimization settings, even the surrounding code. The language standard explicitly leaves the behavior undefined so that the compiler isn't required to handle this code in any particular way. You will get a result, but it's not guaranteed to be consistent from compiler to compiler (or even from run to run).
(int *)marks
cast marks to a int pointer
+ i++
add i at marks (chaging the address pointed) and then increments i by 1
*(...) = i+1
set the VALUE of the cell pointed by our pointer to i+1 (pay attention at the fact that i as already been incremented before, so it will be greater of 2 by the start of the instruction.
I hope this is an example f how you should NOT write the code :)
Let's see.
*((int *)marks + i++) = i+1
-marks is cast to a pointer to int
-i is incremented by one
-the pointer (int *)marks is advanced by the value (i+1) using pointer arithmetic
-this pointer is now dereferenced, so...
-... the memory location to which it points is now written with the value of i+1

Resources