Thread: behavour of --x

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    808

    behavour of --x

    i have the following recursive function
    Code:
    double RFactorial( int Num, int Multiply )
    {
        if ( Num - Multiply == 1 )
            return Num * Multiply;
    
        if ( Num == Multiply )
            return Num;
    
        return Num * Multiply * RFactorial( Num - 1, Multiply + 1 );
    }
    the recursive call wanted num - 1 and multiply - 1 rather than --num and --multiply;

    i got a warning saying the behavior could be undefined or words to that effect

    i thought --x was the same as x -= 1 and meant use that value (whatever x - 1 is) for x from then on. where as x++ was keep x the same value till its finished with in the scope of that variable and then increment it.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > return Num * Multiply * RFactorial( --Num, --Multiply );
    Your understanding of -- and ++ is wrong.

    First of all, you need to understand what a sequence point is.
    Question 3.8
    The side-effects of -- and ++ are fully resolved at sequence point boundaries.

    You might imagine that the blue part happens first, but there's nothing in the standard that says it should be.

    The result is, you have no idea what your expression will result in.

    > i got a warning saying the behavior could be undefined or words to that effect
    Yes, your compiler is correct.
    Heed the warning and fix the code.
    Code:
    $ gcc -Wall -O2 foo.c
    foo.c: In function ‘RFactorial’:
    foo.c:27:41: warning: operation on ‘Num’ may be undefined [-Wsequence-point]
       27 |     return Num * Multiply * RFactorial( --Num, --Multiply );
          |                                         ^~~~~
    foo.c:27:48: warning: operation on ‘Multiply’ may be undefined [-Wsequence-point]
       27 |     return Num * Multiply * RFactorial( --Num, --Multiply );
          |                                                ^~~~~~~~~~
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-26-2023, 10:37 AM
  2. correct behavour of at()
    By sh3rpa in forum C++ Programming
    Replies: 9
    Last Post: 10-22-2007, 02:17 AM

Tags for this Thread