J Cruz Coronel
J Cruz Coronel

Reputation: 23

Conflicting types with double in a function definition

I get an error "conflicting types for 'abs' in my function. The code is very simple.

double abs (double x) {  // Returns absolute value
if (x<0)
    return (x*(-1));
else
    return x;
}

This is on a C proyect on codeblocks. I already tried casting the returns but the error remains anyway.

Upvotes: 2

Views: 1157

Answers (2)

Neil Locketz
Neil Locketz

Reputation: 4328

My guess is you have <stdlib.h> included because abs is already declared there and has the signature int abs(int), so your definition produces "conflicting types".

Upvotes: 5

Chromatix
Chromatix

Reputation: 1151

The problem is not in your code per se. Rather, there is another function already defined named abs() with a different prototype - probably operating on integers. Unlike C++, C doesn't permit function overloading.

I suggest using fabs() from math.h instead. Not only is it already there, but it will typically compile to a single FPU instruction instead of a call and conditional branch.

There is also fabsf() and fabsl() for performing the same operation on float and long double respectively. To use these, you might need to select C99 or C11 mode, as these functions weren't specified in the original ANSI standard.

Upvotes: 4

Related Questions