James Cross
James Cross

Reputation: 7879

passing char[] around functions

I am trying to chain together a few overloaded functions. It is something that should be really simple but I am getting errors. Here is the code:

void output(char c[])
{
    output(c, 0);
}

void output(char c[], int x)
{
    int l = strlen(c) - x;
    output(c, x, l);
}

void output(char c[], int x, int y)
{
    cout << c;
}

int main()
{
    output("myname");
    output("myname", 3);
    output("myname", 2, 4);
}

The errors I am getting relate the chained parts (output(c, 0); and output(c, x, l);. The errors are:

"No matching function for call to 'output (char *&, int)'
"No matching function for call to 'output (char *&, int &, int &)'

An explanation of what I have done wrong would be good as well.

Upvotes: 1

Views: 170

Answers (3)

dmitru
dmitru

Reputation: 371

C++ requires all functions you call to be declared first. You simply can't call a function without the compiler's having seen its declaration (in other words, its prototype) somewhere before in your code.

So, to get it working, you should first declare all your functions (in other words, place all their prototypes), before you call them:

// Declarations go first
void output(char [], int);
void output(char [], int, int);

void output(char c[])
{
    output(c, 0);
}

void output(char c[], int x)
{
    int l = strlen(c) - x;
    output(c, x, l);
}

void output(char c[], int x, int y)
{
    cout << c;
}

That way, the compiler will get all needed prototypes before calling the functions.

Upvotes: 0

besworland
besworland

Reputation: 765

You must first define all the functions that will be used later on. So in your case I would suggest to define function prototypes first, and later on to implement all of them. Here is what I mean:

void output(char c[], int x);
void output(char c[], int x, int y);

void output(char c[])
{
    output(c, 0);
}

void output(char c[], int x)
{
    int l = strlen(c) - x;
    output(c, x, l);
}

void output(char c[], int x, int y)
{
    std::cout << c;
}

int main()
{
    output("myname");
    output("myname", 3);
    output("myname", 2, 4);
}

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727037

I think the problem has to do with the fact that your functions lack prototypes. In cases like that, you should re-order functions so that the ones you call appear ahead of the ones that call them:

void output(const char c[], int x, int y)
{
    cout << c;
}
void output(const char c[], int x)
{
    int l = strlen(c) - x;
    output(c, x, l);
} 
void output(const char c[])
{
    output(c, 0);
}

But it is best to stick to using prototypes for all functions ahead of defining them.

Also note that string literals are const. Since your functions do not modify the content of string literals, you should declare const char c[] instead of char c[].

Upvotes: 7

Related Questions