Pregunta

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;
}
¿Fue útil?

Solución

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

Otros consejos

Functions must at least be declared before they are used, preferably using prototype syntax (which specifies the number and types of arguments, as well as the return type). So at the very least, you need a line like

double abs( double number ); 

somewhere in your code before you call abs in main.

You may also define a function before it is used:

double abs( double number )
{
   // compute absolute value
}

int main( void )
{
  ...
  x = abs(x);
  ...
}

This is actually my preference; everything in the same translation unit (file) should be defined before it's used. This way you don't have to worry about keeping declarations and definitions in sync.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top