# difference between cnt++,++cnt

Page 1 of 1

## 2 Replies - 13664 Views - Last Post: 23 April 2007 - 10:43 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=27054&amp;s=1de2b2c4fe18e73ca28222a147f9fe08&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 viggu212

Reputation: 2
• Posts: 7
• Joined: 21-April 07

# difference between cnt++,++cnt

Posted 23 April 2007 - 08:30 AM

printf(" %d %d %d ",++cnt,cnt++,cnt);
Is This A Good Question/Topic? 0

## Replies To: difference between cnt++,++cnt

### #2 BitByte

Reputation: 11
• Posts: 194
• Joined: 09-August 06

## Re: difference between cnt++,++cnt

Posted 23 April 2007 - 08:50 AM

I don't know C but maybe this will explain it for you

```#include <iostream>

int main()
{
int a = 10;
int b = 20;

// a and b get incremented AFTER any operations on the variables occurs
// Result: a = 10, b = 20
std::cout << "a = " << a++ << ", b = " << b++ << std::endl;

// In memory they are imcremented but won't show until the next output
// Ouput: a = 11, b = 21
std::cout << "a = " << a << ", b = " << b << std::endl;

// Reset a and b
a = 10, b = 20;

// a and b get incremented BEFORE any operations on the variables occurs
// Result: a = 11, b = 21
std::cout << "a = " << ++a << ", b = " << ++b << std::endl;

return 0;
}

```

Hope it helps

### #3 NickDMax

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: difference between cnt++,++cnt

Posted 23 April 2007 - 10:43 AM

First off the line you have written: printf(" %d %d %d ",++cnt,cnt++,cnt); has undefined behavior in ANSI C. The reason is that ANSI C does not state in which order the compiler must evaluate the arguments to a function. So one one compiler it will do them is order ++cnt, cnt++, cnt and on another it will do them in the reverse order.

In general you should avoid using the ++, and -- operators on the same variable in the same line of code. Anything like i = ++i or value = ++i * i++ will PROBABLY work, but its behavior will change from compiler to compiler.

Now to answer the question what do ++cnt and cnt++ do. The first one (++cnt) is called pre-increment this means that it incriments cnt BEFORE it is used in the current expression. Try very hard not to use the ++ and -- operators in multipart expresions unless you really understand the rules.

so in the code
```int cnt=5;
int value = ++cnt;
printf("value = %d, cnt=%d\n", value, cnt);
```
value will be equal to 6, and cnt will be equal to 6. but in the code
```int cnt=5;
int value = cnt++;
printf("value = %d, cnt=%d\n", value, cnt);
```
Here value will be 5, and cnt will be 6 because this was a POST-increment. cnt was incremented AFTER the value was used in the expresion.