return value from function became garbage

Discussion in 'C Programming' started by sandeep_agarwal, Jul 11, 2008.

  1. sandeep_agarwal


    Jul 11, 2008

    I came across a funny problem today so thought of sharing with you guys.

    I defined a function, something like this:

    double calculateSomething(long a, long b, long c, long d)
    double val = -1;
    //do some calculation using a, b, c, d
    //and store the return value in val
    return val;

    This function was called from fun1().

    void fun1()
    double amt = -1;
    amt = calculateSomething(a, b, c, d); //The amt variable had proper value

    There was another function also lets say fun2() with the same definition as
    fun1 but defined above the calculateSomething function.

    void fun2() //Defined above definition of fun2()
    double amt = -1;
    amt = calculateSomething(a, b, c, d); //The amt variable had improper value

    Here the amt variable had some garbage value. I am using the gcc compiler and didnt do any forward declaration of the calculateSomething() function.

    Here I expected that compiler should have given me an error but it gives a warning and takes an implicit declaration to return int.
    The warning that it gives is
    warning: `calculateSomething' was previously implicitly declared to return `int

    I refer this problem as funny because it compiles properly and also while debugging I found that it goes in that function properly and calculates and returns the value correctly but after the value is returned in the local variable inside fun2 it becomes garbage.

    This may seem like a trivial problem but it wasted some of my time as there are too many warnings in my program so I missed this one ;-)

    The problem got solved after i put the declaration in the header file.
    Last edited: Jul 11, 2008
    sandeep_agarwal, Jul 11, 2008
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page