difference between cnt++,++cnt

please can anyonr tell me the difference between the post-increment an

Page 1 of 1

2 Replies - 5709 Views - Last Post: 23 April 2007 - 10:43 AM Rate Topic: -----

#1 viggu212  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • 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  Icon User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • 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
Was This Post Helpful? 0
  • +
  • -

#3 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1