++ operator

C

Cadderly

Hi,

Could you explain why the outputs of the 2 'for' are the same?
Thanks

#include <stdio.h>
int main(void)
{
int i;
for ( i = 0; i < 5; i++ ) {
printf("%d \n", i);
}

for ( i = 0; i < 5; ++i ) {
printf("%d \n", i);
}

return 0;
}
 
S

Simon Biber

Cadderly said:
Could you explain why the outputs of the 2 'for' are
the same?

#include <stdio.h>
int main(void)
{
int i;
for ( i = 0; i < 5; i++ ) {
printf("%d \n", i);
}
for ( i = 0; i < 5; ++i ) {
printf("%d \n", i);
}
return 0;
}

The value of i++ and ++i are different, but their effect
is the same. In the third part of the for statement, only
the effect matters; the value is discarded.
 
J

Joona I Palaste

Cadderly said:
Could you explain why the outputs of the 2 'for' are the same?
Thanks

Because outside of the value returned, i++ and ++i have the same
effect. i gets incremented by one.
#include <stdio.h>
int main(void)
{
int i;
for ( i = 0; i < 5; i++ ) {
printf("%d \n", i);
}
for ( i = 0; i < 5; ++i ) {
printf("%d \n", i);
}
return 0;
}

--
/-- Joona Palaste ([email protected]) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"A computer program does what you tell it to do, not what you want it to do."
- Anon
 
M

Matt Gregory

Cadderly said:
Hi,

Could you explain why the outputs of the 2 'for' are the same?
Thanks

If you changed it to:

#include <stdio.h>
int main(void)
{
int i;
int n;

for ( n = i = 0; i < 5; n = i++ ) {
printf("%d \n", n);
}

for ( n = i = 0; i < 5; n = ++i ) {
printf("%d \n", n);
}

return 0;
}

then they would be different.
 
D

dharmender rai

Here is the explanation:
for ( i = 0; i < 5; i++ ) {
printf("%d \n", i);
}

is actually
for ( i = 0; i < 5; ) {
printf("%d \n", i);
i++;
}

AND

for ( i = 0; i < 5; ++i ) {
printf("%d \n", i);
}
is
for ( i = 0; i < 5; ) {
printf("%d \n", i);
++i;
}

-- Dharmender Rai
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,217
Latest member
topweb3twitterchannels

Latest Threads

Top