Search code examples
cfunctiondebuggingdeclarationabsolute-value

Intro to C: Declaration of Functions


I want to declare a function for use in my code in ANSI C. Am I allowed to define the function after using it in main()? For example an absolute value function that I wrote: can anyone tell me if it's sound?

#include <stdio.h>

int main()
{
    double value1 = -5;
    printf("%lf",
           abs(value1));
}

double abs(double number)
{
    if (number < 0) {
        (number * (-1) = number);
    }
    return number;
}

Solution

  • You need to fix a couple of things:

    #include <stdio.h>
    
    double abs(double number); // <<< 1. prototype here
    
    int main()
    {
        double value1 = -5;
    
        printf("%lf",
               abs(value1));
    }
    
    double abs(double number)
    {
        if (number < 0) {
            number = number * -1.0; // <<< 2. fix here
        }
        return number;
    }
    
    1. the abs function needs a prototype so that the compiler knows its function signature before you call it

    2. your expression for negating number was back-to-front