-3

I'm a student, starting to learn C++ with some previous C knowledge. I have a working C++ code written in C style, that has an oveloaded function for input either a double or a string:

#include "stdio.h"
#include "string.h"
#include "ctype.h"

const int STR_LEN = 7;
int try_to_input(double* real_number);
int try_to_input(char (*string)[STR_LEN]);//line 16

int main()
{
    return 0;
}

int try_to_input(double* real_number) {//line 35
    int attempts_for_input = 3;
    //stops when == 0
    while (attempts_for_input) {
        //if input unsuccessful
        if (scanf_s("%lf", real_number) == 0) {
            puts("Invalid input! Try again.");
            attempts_for_input--;
            //flush stdin
            int tmp;
            while ((tmp = getchar()) != EOF && tmp != '\n');
            //extra '\n' after that for some reason
        }
        else return 0;
    }
    return -1;
}

int try_to_input(char (*string) [STR_LEN] ) { //line 53
    int attempts_for_input = 3;

    while (attempts_for_input) {
        if (gets_s(*string, STR_LEN) == NULL) {
            puts("Invalid input! Try again.\n");
            attempts_for_input--;
            //flush stdin
            int tmp;
            while ((tmp = getchar()) != EOF && tmp != '\n');
        }
        else return 0;
    }
    return -1;

}

But when I compile it as C, it gives me the following errors:

(16): warning C4028: formal parameter 1 different from declaration
(35): warning C4028: formal parameter 1 different from declaration
(53): error C2084: function 'int try_to_input(double *)' already has a body
(35): note: see previous definition of 'try_to_input'


What could be the problem? What's wrong with my overloading?
Sam
  • 1,832
  • 19
  • 35

2 Answers2

3

I have a working C++ code written in C style, that has an oveloaded function [..]

Stop it right there!

C does not support function overloading, thus the compilation error. Read more in Does C support overloading?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • I will upvote, but I should give credit to the guy who answered that in the comments like a year ago. Thanks for the link, though – Sam Sep 12 '17 at 10:08
  • @Sam the question popped up in the questions' feed when you answered, and I didn't check the comments, nor the post date. – gsamaras Sep 12 '17 at 11:26
  • Sure. But turns out it's a duplicate – Sam Sep 12 '17 at 11:29
0

As Jonathon Reinhart commented, turns out, C language simply does not support overloaded functions.

user694733
  • 15,208
  • 2
  • 42
  • 68
Sam
  • 1,832
  • 19
  • 35
  • I'm confused whether I should accept my answer or wait for John – Sam Sep 12 '17 at 10:07
  • You should always select the answer that best answers your question (even if it's your own). Comments are often abused for answers, which not what they are intended for, so you can safely ignore them when selecting an answer. – user694733 Sep 13 '17 at 10:51