Postfix and Prefix operator with respect to functions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • swapnaoe
    New Member
    • Jul 2006
    • 21

    Postfix and Prefix operator with respect to functions

    Hi,

    In http://elearning.embnet.org/file.php...---and---.html I read about postfix and prefix unary operators.

    It said " If the increment or decrement operator is used as a prefix, the operation is performed before the function call. If the operator is used as a postfix, the operation is performed after the function call. "

    So accordingly
    int x=4;
    printf("%d%d", x++,x++);
    the output should be 4 4

    But it is never so in C. The output would rather be 5, 4.
    But it applies to C++. I tried in VC++, the postfix operation indeed is performed after the function call.

    What do you guys have to say on this?
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    I would say what I'm sure Banfa and many other experts would say: You have invoked undefined behavior. Using pre- or post-increment operators twice in the same statement means that you cannot predict exactly what the result will be. I suspect the differences you are seeing between C and C++ might have something to do with the way your compilers interpret these statements.

    Basically, don't write statements like this.

    Comment

    • swapnaoe
      New Member
      • Jul 2006
      • 21

      #3
      Alright. Please consider this example.

      void main()
      {
      int x=4;
      func(x,x++);
      }
      func(int x, int y)
      {
      /*Some definition*/
      printf("%d\t%d\ n",x,y);
      }
      -----------------------------------------------------------------------------------------------------------------
      My concern was about the statement which i quoted in my prevoius post.According to it, the calling func() would pass 4 and 4 not 5 and 4.

      Like i mentioned before,when i ran this in MSVC++6.0 , it is passing 4 and 4 not 5 and 4. I was wondering if there is really a difference for increment and decrement operators when it comes to different programming languages.(c, c++).

      I am convinced with the way increment and decrement operators work in C.
      That statement just made me curious.

      Comment

      Working...