Why does my function produces a Conflicting Types error?

Viewed 422

I tried to reproduce the function atof() from the C language book without looking at it, i wrote it and every line of code seemed to be right, but when I compile the program it tells me that there is a conflicting type error .

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

float atof(char s[]); // the error is produced here

int main()
{
    char line[100] = "672";
    float num = atof(line);

    printf("%f", num);
    return 0;
}

// I didn't finish the function yet...
float atof(char s[])
{
    int i, sign;
    float n;
    for(i = 0; s[i] == ' '; i++)  // skip white spaces
        ;
    // set sign to the -1 if it is negative, 1 if else
    sign = (s[i] == '-') ? -1 : 1;
    if(s[i] == '+' || s[i] == '-')
        i++;
    for(n = 0.0; isdigit(s[i]); i++)
    {
        n = 10.0 * n + (s[i] - '0');
    }
    return n * sign;
}

What I tried :

  • I thought that the problem occurred because this function already exists in one of the libraries that I included, so I changed it name to strtof() and the problem was the same .
  • I tried to change the type of the function instead but the problem was still there .
  • I tried to return a float return 2.5F and double return 2.5 but that didn't solve the issue .

( btw I use gcc compiler version 9.2.0 )

2 Answers

I thought that the problem occurred because this function already exists in one of the libraries that I included, so I changed it name to strtof() and the problem was the same .

You are almost there: strtof() and atof() are both library functions for your platform. use something like my_strtof() or my_atof().

Reference:

and both are standard C library functions.

The C Standard already contains a function with the name atof in the header <stdlib.h>.

It is declared like

#include <stdlib.h>
double atof(const char *nptr);

So your function declaration conflicts with the C standard function declaration with the same name.

You need to rename your function.

And declare the parameter with the qualifier const the same way as the parameter of the standard function is declared.

Also pay attention that there is a typo in your function.

Instead of the assignment in this statement

sign = (s[i] = '-') ? -1 : 1;

there shall be comparison

sign = (s[i] == '-') ? -1 : 1;
Related