Thread: C function bug

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    13
    Rep Power
    0

    Question C function bug


    Dear All,
    Please advise on the following piece of code:
    short d;
    double fn(int n) {
    short i=--n;
    return 1.0/i--+n;
    }

    can anyone explain what the function is actually doing? im perplexed! why have int and not short in the code?
  2. #2
  3. jasondoucette.com
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2003
    Location
    Canada
    Posts
    378
    Rep Power
    12
    mp16, when a program does not work as expected, there is more than a 99.99% chance that it is the fault of the code you wrote, and not a "c function bug", so please stop posting threads with this title. In the case of this thread, the question you are asking is not even referrering to a possible bug, so the title makes no sense whatsoever... Please post appropriate titles from now on.

    Regarding your code:

    Code:
    short d;
    This is not even used.

    Code:
    double fn(int n)
    This is a function that takes an int as a parameter and returns a double.

    The function code:
    Code:
    short i=--n;
    This decrements n by one BEFORE it is used in the expression (because the -- preceeds it. if it had been n--, then it would be decremented AFTER it is used in the expression). The result is stored to i.

    Code:
    return 1.0/i--+n;
    This decrements i AFTER it is used by the expresson (which makes no sense, because i is not used after this expression), because -- follows i instead of preceeding it. i is divided into 1.0, and n is added to it. The result is not stored anywhere - it is immediately returned by the function.

    Please explain why you wish to know what the above function does? It appears to be a homework assignment. If you do not understand the above, then you do not understand elementary C syntax, and I would suggest going through a C tutorial to learn these basics. This board is not meant to answer homework questions.

IMN logo majestic logo threadwatch logo seochat tools logo