I accidentally covered the numbers with these instead of the curly brackets normally used and got "2 4 0 0". Why does this shifting happen?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int a[2][2]={(1,2),(3,4)};
for (int i = 0; i < 2; ++i)
{
/* code */
for (int j = 0; j < 2; ++j)
{
/* code */
printf("%d ",a[i][j] );
}
}
return 0;
}
In the braces of the list initialization in this declaration
int a[2][2]={(1,2),(3,4)};
there are present two expressions ( 1, 2 ) and ( 3, 4 ). They are primary expressions with the comma operator.
According to the C Standard (6.5.17 Comma operator)
2 The left operand of a comma operator is evaluated as a void
expression; there is a sequence point between its evaluation and that
of the right operand. Then the right operand is evaluated; the result
has its type and value
So the values of the expressions are 2 and 4.
Thus in fact you have
int a[2][2]={ 2, 4 };
As a result the first sub-array of the array that is the array a[0] is initialized with these values. Elements of the second sub array a[1] are zero initialized.
If for example you would write
int a[2][2]={(1,2,3,4)};
then this declaration is equivalent to
int a[2][2]={ 4 };
and only the element a[0][0] will be explicitly initialized by the value 4,
Another example of using an expression with the comma operator as an initializer.
int i = 0;
int j = ( i++, i++, i++ );
As a result i will be equal to 3 and j to 2.
You accidentally used the comma operator. In your case it did nothing, but the resulting value from it is the last value in the comma separated list: (1,2) results in the last value 2 and (3,4) results in 4.
So your code was equivalent to:
int a[2][2]={2,4};
The last two of the four values in a were not provided, so they were initialized implicitly with zeroes. This post explains exactly why.
What will be the output of the program?
#include<stdio.h>
void main()
{
int i = 0;
while(i < 10)
{
i++;
printf("%d\n",i);
}
}
Will the output start from 0 or from 1 as I my professor taught me that the value of the variable is incremented only at the end of the loop while using i++ unlike in ++i?
The side effect of incrementing using either the prefix ++ or the postfix ++ occurs before the statement i++; completes. The fact that the statement is in a loop doesn't change that.
Your professor is correct. The first time printf is called in the loop, i will have the value 1 because the previous statement incremented the value.
Had you instead had the following code:
while(i < 10)
{
printf("%d\n",i++);
}
Then 0 would be printed on the first iteration. In this case, the value of i is incremented, but the postfix ++ operator means that the old value of i is passed to the printf call.
will start from 1 since the line i++ ends before you enter the next line which prints, the ++i compared to i++ is different when you increment it while doing something else in the same line/command.
for example: if you use
printf("%d",i++);
it would print 0 before incrementing i but if you put it like this:
printf("%d",++i);
it will first increment i (from 0 to 1) and then print i(which is 1 the first time it's printed).
Your code will print 1 as first value.
i++ increments the value at the end of the statement, and vice versa ++i increments the value before the statement. This is usually used when assigning variables:
i = 5;
int a = ++i; // a=6, i=6
i = 5;
int b = i++; // b=5, i=6
In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?
++i will increment the value of i, and then return the incremented value.
i = 1;
j = ++i;
(i is 2, j is 2)
i++ will increment the value of i, but return the original value that i held before being incremented.
i = 1;
j = i++;
(i is 2, j is 1)
For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R.
In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.
There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.
The efficiency question is interesting... here's my attempt at an answer:
Is there a performance difference between i++ and ++i in C?
As #OnFreund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.
i++ is known as post increment whereas ++i is called pre increment.
i++
i++ is post increment because it increments i's value by 1 after the operation is over.
Let’s see the following example:
int i = 1, j;
j = i++;
Here value of j = 1, but i = 2. Here the value of i will be assigned to j first, and then i will be incremented.
++i
++i is pre increment because it increments i's value by 1 before the operation.
It means j = i; will execute after i++.
Let’s see the following example:
int i = 1, j;
j = ++i;
Here the value of j = 2 but i = 2. Here the value of i will be assigned to j after the i incremention of i.
Similarly, ++i will be executed before j=i;.
For your question which should be used in the incrementation block of a for loop? the answer is, you can use any one... It doesn't matter. It will execute your for loop same number of times.
for(i=0; i<5; i++)
printf("%d ", i);
And
for(i=0; i<5; ++i)
printf("%d ", i);
Both the loops will produce the same output. I.e., 0 1 2 3 4.
It only matters where you are using it.
for(i = 0; i<5;)
printf("%d ", ++i);
In this case output will be 1 2 3 4 5.
i++: In this scenario first the value is assigned and then increment happens.
++i: In this scenario first the increment is done and then value is assigned
Below is the image visualization and also here is a nice practical video which demonstrates the same.
++i increments the value, then returns it.
i++ returns the value, and then increments it.
It's a subtle difference.
For a for loop, use ++i, as it's slightly faster. i++ will create an extra copy that just gets thrown away.
Please don't worry about the "efficiency" (speed, really) of which one is faster. We have compilers these days that take care of these things. Use whichever one makes sense to use, based on which more clearly shows your intent.
The only difference is the order of operations between the increment of the variable and the value the operator returns.
This code and its output explains the the difference:
#include<stdio.h>
int main(int argc, char* argv[])
{
unsigned int i=0, a;
printf("i initial value: %d; ", i);
a = i++;
printf("value returned by i++: %d, i after: %d\n", a, i);
i=0;
printf("i initial value: %d; ", i);
a = ++i;
printf(" value returned by ++i: %d, i after: %d\n",a, i);
}
The output is:
i initial value: 0; value returned by i++: 0, i after: 1
i initial value: 0; value returned by ++i: 1, i after: 1
So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.
Another example:
#include<stdio.h>
int main ()
int i=0;
int a = i++*2;
printf("i=0, i++*2=%d\n", a);
i=0;
a = ++i * 2;
printf("i=0, ++i*2=%d\n", a);
i=0;
a = (++i) * 2;
printf("i=0, (++i)*2=%d\n", a);
i=0;
a = (i++) * 2;
printf("i=0, (i++)*2=%d\n", a);
return 0;
}
Output:
i=0, i++*2=0
i=0, ++i*2=2
i=0, (++i)*2=2
i=0, (i++)*2=0
Many times there is no difference
Differences are clear when the returned value is assigned to another variable or when the increment is performed in concatenation with other operations where operations precedence is applied (i++*2 is different from ++i*2, as well as (i++)*2 and (++i)*2) in many cases they are interchangeable. A classical example is the for loop syntax:
for(int i=0; i<10; i++)
has the same effect of
for(int i=0; i<10; ++i)
Efficiency
Pre-increment is always at least as efficient as post-increment: in fact post-increment usually involves keeping a copy of the previous value around and might add a little extra code.
As others have suggested, due to compiler optimisations many times they are equally efficient, probably a for loop lies within these cases.
Rule to remember
To not make any confusion between the two operators I adopted this rule:
Associate the position of the operator ++ with respect to the variable i to the order of the ++ operation with respect to the assignment
Said in other words:
++ before i means incrementation must be carried out before assignment;
++ after i means incrementation must be carried out after assignment:
The reason ++i can be slightly faster than i++ is that i++ can require a local copy of the value of i before it gets incremented, while ++i never does. In some cases, some compilers will optimize it away if possible... but it's not always possible, and not all compilers do this.
I try not to rely too much on compilers optimizations, so I'd follow Ryan Fox's advice: when I can use both, I use ++i.
The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.
In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.
However, you should consider two main problems with the preceding logic.
Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.
In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.
In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.
This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."
++i: is pre-increment the other is post-increment.
i++: gets the element and then increments it.
++i: increments i and then returns the element.
Example:
int i = 0;
printf("i: %d\n", i);
printf("i++: %d\n", i++);
printf("++i: %d\n", ++i);
Output:
i: 0
i++: 0
++i: 2
++i (Prefix operation): Increments and then assigns the value
(eg): int i = 5, int b = ++i
In this case, 6 is assigned to b first and then increments to 7 and so on.
i++ (Postfix operation): Assigns and then increments the value
(eg): int i = 5, int b = i++
In this case, 5 is assigned to b first and then increments to 6 and so on.
Incase of for loop: i++ is mostly used because, normally we use the starting value of i before incrementing in for loop. But depending on your program logic it may vary.
i++ and ++i
This little code may help to visualize the difference from a different angle than the already posted answers:
int i = 10, j = 10;
printf ("i is %i \n", i);
printf ("i++ is %i \n", i++);
printf ("i is %i \n\n", i);
printf ("j is %i \n", j);
printf ("++j is %i \n", ++j);
printf ("j is %i \n", j);
The outcome is:
//Remember that the values are i = 10, and j = 10
i is 10
i++ is 10 //Assigns (print out), then increments
i is 11
j is 10
++j is 11 //Increments, then assigns (print out)
j is 11
Pay attention to the before and after situations.
for loop
As for which one of them should be used in an incrementation block of a for loop, I think that the best we can do to make a decision is use a good example:
int i, j;
for (i = 0; i <= 3; i++)
printf (" > iteration #%i", i);
printf ("\n");
for (j = 0; j <= 3; ++j)
printf (" > iteration #%i", j);
The outcome is:
> iteration #0 > iteration #1 > iteration #2 > iteration #3
> iteration #0 > iteration #1 > iteration #2 > iteration #3
I don't know about you, but I don't see any difference in its usage, at least in a for loop.
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int i;
int j;
Increment operators:
i = 1;
j = ++i; // i is now 2, j is also 2
j = i++; // i is now 3, j is 2
Shortly:
++i and i++ works same if you are not writing them in a function. If you use something like function(i++) or function(++i) you can see the difference.
function(++i) says first increment i by 1, after that put this i into the function with new value.
function(i++) says put first i into the function after that increment i by 1.
int i=4;
printf("%d\n",pow(++i,2));//it prints 25 and i is 5 now
i=4;
printf("%d",pow(i++,2));//it prints 16 i is 5 now
Pre-crement means increment on the same line. Post-increment means increment after the line executes.
int j = 0;
System.out.println(j); // 0
System.out.println(j++); // 0. post-increment. It means after this line executes j increments.
int k = 0;
System.out.println(k); // 0
System.out.println(++k); // 1. pre increment. It means it increments first and then the line executes
When it comes with OR, AND operators, it becomes more interesting.
int m = 0;
if((m == 0 || m++ == 0) && (m++ == 1)) { // False
// In the OR condition, if the first line is already true
// then the compiler doesn't check the rest. It is a
// technique of compiler optimization
System.out.println("post-increment " + m);
}
int n = 0;
if((n == 0 || n++ == 0) && (++n == 1)) { // True
System.out.println("pre-increment " + n); // 1
}
In Array
System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 };
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); // 12
jj = a[1]++; // 12
System.out.println(a[1]); // a[1] = 13
mm = a[1]; // 13
System.out.printf("\n%d %d %d\n", ii, jj, mm); // 12, 12, 13
for (int val: a) {
System.out.print(" " + val); // 55, 13, 15, 20, 25
}
In C++ post/pre-increment of pointer variable
#include <iostream>
using namespace std;
int main() {
int x = 10;
int* p = &x;
std::cout << "address = " << p <<"\n"; // Prints the address of x
std::cout << "address = " << p <<"\n"; // Prints (the address of x) + sizeof(int)
std::cout << "address = " << &x <<"\n"; // Prints the address of x
std::cout << "address = " << ++&x << "\n"; // Error. The reference can't reassign, because it is fixed (immutable).
}
I assume you understand the difference in semantics now (though honestly I wonder why
people ask 'what does operator X mean' questions on stack overflow rather than reading,
you know, a book or web tutorial or something.
But anyway, as far as which one to use, ignore questions of performance, which are
unlikely important even in C++. This is the principle you should use when deciding
which to use:
Say what you mean in code.
If you don't need the value-before-increment in your statement, don't use that form of the operator. It's a minor issue, but unless you are working with a style guide that bans one
version in favor of the other altogether (aka a bone-headed style guide), you should use
the form that most exactly expresses what you are trying to do.
QED, use the pre-increment version:
for (int i = 0; i != X; ++i) ...
The difference can be understood by this simple C++ code below:
int i, j, k, l;
i = 1; //initialize int i with 1
j = i+1; //add 1 with i and set that as the value of j. i is still 1
k = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1
l = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.
cout << i << ' ' << j << ' ' << k << ' '<< l << endl;
return 0;
The Main Difference is
i++ Post(After Increment) and
++i Pre (Before Increment)
post if i =1 the loop increments like 1,2,3,4,n
pre if i =1 the loop increments like 2,3,4,5,n
In simple words the difference between both is in the steps take a look to the image below.
Example:
int i = 1;
int j = i++;
The j result is 1
int i = 1;
int j = ++i;
The j result is 2
Note: in both cases i values is 2
You can think of the internal conversion of that as multiple statements:
// case 1
i++;
/* you can think as,
* i;
* i= i+1;
*/
// case 2
++i;
/* you can think as,
* i = i+i;
* i;
*/
a=i++ means a contains the current i value.
a=++i means a contains the incremented i value.
{
int i=0;
int j;
j=(i=0)?2:3;
printf("the answer is %d",j);
}
I want to know why this statement j=(i=0)?2:3; gives the answer 3 when the value define to i is zero?
In C, zero is considered as false and all non-zero numbers are considered as true. This:
j=(i=0)?2:3;
is the same as
if(i = 0)
j = 2;
else
j = 3;
Here, i = 0 assigns 0 to i and since 0 is considered as false, the else executes, assigning 3 to j.
Do note that = is the assignment operator and assigns its left and right operands. This is different from the conditional operator == which compares both its operands and returns 0 if false and 1 if true.
If you meant ==, then j=(i==0)?2:3; is the same as
if(i == 0)
j = 2;
else
j = 3;
which will assign 2 to j as i == 0 is true.
To prevent these kind of mistakes, you can use Yoda Conditions as suggested by #JackWhiteIII, i.e , reversing the condition. For example,
j=(i=0)?2:3;
can be written as
j=(0=i)?2:3;
Since 0 is a constant value and cannot be altered, the compiler is emit an error, preventing these kind of mistakes. Note that both 0 == i and i == 0 do the same thing and both are indeed valid.
i=0 is an assignment. Use i==0 for comparison.
Assignments return the new value of the variable that is being assigned to. In your case, that's 0. Evaluated as a condition, that's false.
As in the above code snippet,
{
int i=0;
int j;
j=(i=0)?2:3;
printf("the answer is %d",j);
}
you mistyped, (i==0) with (i=0) which just assigns 0 to i and checks the result, hence you're getting the output as, the answer is 3. The new code would be like,
{
int i=0;
int j;
j=(i==0)?2:3;
printf("the answer is %d",j);
}
The above corrected code snipped gives the output as,
the answer is 2.
Because you mistyped the == operator. You are setting i to the value 0 again and testing this value, which is 0, hence false.
Write this instead:
j = (i == 0) ? 2 : 3;
The result of the assignment operator (= in i=0) is the new value of the object (0). 0 is a false value, thus the 'false' branch of your condition is chosen, which is 3.
This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 8 years ago.
I can't understand how this works and why it produces
the following output.
int main()
{
int i=0;
int a=5;
int x=0;
for(i=0; i<5; x=(i++,a++))
{
printf("i=%d a=%d x=%d\n",i,a,x);
}
}
this give as output:
i=0 a=5 x=0
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8
Forget about the ++ for the moment, they're just a distraction.
int a = 5;
int i = 0;
int x = (i, a);
Sets the value of x to 5. The i is evaluated and discarded, then the a is evaluated and assigned to x.
In your loop, the post-increment a++ does what it always does; returns the current value and then increments the variable. So x takes the value of a before it is incremented, then a's value is increased by 1. Because i++ was also evaluated, its value increases as well.
I suppose you understand a for loop like this:
for(i=0; i<5; i++)
you might as well want to increment two variables; if you separate them with a comma; like this:
for(i=0; i<5; i++,a++)
at the start of each loop, both i and a will be incremented. Now only the expression x=(i++,a++) needs to be explained:
x gets the last of both values assigned. It is the same as writing:
x=i++;
x=a++;
of course a is post-incremented so first its value is assigned to x; and only then a is incremented.
It is simple both the operators that you have used are 'Post Increment', this means that assignment will happen first then the increment in variable will happen.
Let us understand with an example,
Suppose,
i=5
x=i++;
printf("%d", x)
The above code will give output as 5
and
i=5
x=++i;
printf("%d", x)
and this will give output as 6.
Hope you understand the logic.
The comma operator means: execute all, and return the last value;
Example:
A = (b+=1,c+2,d+1);
This sentence will add 1 to b, sum 2 to c (but will not modify it) and sum 1 to d. Hence d+1 is the last expression A will be set to its value.
The post and pre operator ++ are tricky.
A++ means: return the value of A and after that, you increment it.
++A means: increment A and then return the value of it.
so if A=2
b=A++; // set b to 2 and increments A one unity
b=++A; // increments A to 4 and sets b to 4
Consider your example and the output (except I made the initial value of x to be 22):
int i=0;
int a=5;
int x=22;
for(i=0; i<5; x=(i++,a++))
{
printf("i=%d a=%d x=%d\n",i,a,x);
}
Prints:
i=0 a=5 x=22
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8
Notice that x has either the initial value of x prior to the loop or the previous value from the last trip through the loop.
Recall that any for loop can be expressed as an equivelent while loop.
The for loop of:
for(exp 1; exp 2; exp 3){
expressions
}
Is equivalent to:
exp 1;
while(exp 2){
expressions
exp 3;
}
So your for loop can be written as:
int i=0; // exp 1 from the for loop
int a=5;
int x=22;
while(i<5){ // exp 2
// loop body
printf("i=%d a=%d x=%d\n",i,a,x);
x=(i++,a++); // exp 3 from the for loop
}
Prints same output.
The fact that exp 3 is evaluated at the end of the loop (whether it is a for or while loop) is why x has the previous value of x in the body of the loop.
The final thing to consider is the comma operator. The expression:
i=(a+=2, a+b)
^^^ evaluate a then add 2
^ comma operator in this case
^^ add b to a
^ store the final expression -- the RH of the comma operator --
into i