0

I have following function in my include (.h) file:

string genPassword(char[] alphabet = {}, int length=0)
{
    string s = "";
     for (int i = 0; i < length; ++i) {
        s += alphabet[rand() % (sizeof(alphabet) - 1)];
    }
    random_shuffle(s.begin(), s.end());
    return s;
}   

When I try to compile it with g++ (to check is everything working) I see following errors:

g++ -Wall -c "passfunctions.h" (w katalogu /home/bla/programs)

passfunctions.h:22:27: error: expected ‘,’ or ‘...’ before ‘alphabet’

string genPassword(char[] alphabet = {}, int length=0)

                       ^

passfunctions.h: In function ‘std::string genPassword(char*)’:

passfunctions.h:25:23: error: ‘length’ was not declared in this scope

for (int i = 0; i < length; ++i) {

                   ^

passfunctions.h:26:14: error: ‘alphabet’ was not declared in this scope

     s += alphabet[rand() % (sizeof(alphabet) - 1)];

          ^

Compilation failed.

I do not understand those errors. Why semicolon is expected before alphabet in function declaration?...

Why two next errors shows the variables declared in function are "not declared in this scope"? Please explain me what do I do wrong.

TN888
  • 7,659
  • 9
  • 48
  • 84

2 Answers2

1

The syntax is wrong. You need something like

string genPassword(char alphabet[] = {}, int length=0);
                                ^^

Note 1: This is a function declaration. If you have a separate function definition, omit the default parameter values:

string genPassword(char alphabet[], int length) { .... }

If you want to define the function at the point of declaration in the header, then mark it inline to avoid multiple definitions:

inline string genPassword(char alphabet[] = {}, int length=0)
{
  ....
}

Note 2: alphabet is really a char* in this context, so it may make sense to set the default value to nullptr. Also note that sizeof(alhpabet) is the size of a char*, not the size of an array (thanks to @RaymondChen for pointing that out.)

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    Note also that since `alphabet` is a `char *`, the `sizeof(alphabet)` does not do what you think. – Raymond Chen Jul 03 '14 at 12:33
  • Not formally wrong, but since he's not modifying `alphabet` in his function (and it probably makes sense to call the function with a string literal), it should really be `char const* alphabet`. – James Kanze Jul 03 '14 at 12:50
0

You must declare default arguments in the function declaration. Try this in your header:

string genPassword(char[] = {}, int length=0);

And then define it like this in your .cpp file:

string genPassword(char* alphabet, int length)
{
    ...
}
yizzlez
  • 8,757
  • 4
  • 29
  • 44