HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

String literals as char arrays

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
literalschararraysstring

Problem

Is it considered bad practice to pass string literals as char*, when an array and not a c-string is expected by the function? From my code:

char ConsoleIO::GetNextChar(string prompt, char* choices, int numChoices) {
    // Loop until valid input, or 10 times.
    for (int i = 0; i < 10; i++) {
        Write(prompt);

        char* buffer = new char[200];
        cin.getline(buffer, 200);
        char choice = tolower(buffer[0]);

        if (in(choice, choices, numChoices)) {
            return choice;
        }

        WriteLine("Invalid choice.");
    }
    // Just return the first choice as the default.
    return choices[0];
}

// In main:
char userChoice = ConsoleIO::GetNextChar("Make a selection: ", "234", 3);


It compiles, but is it bad practice?

Solution

When a C or C-related programmer sees char* they're going to naturally think of passing in a C-string. In my opinion, it's absolutely fine to do that. If you want to invoke an array of characters in C, I'd do it like this:

char ConsoleIO::GetNextChar(string prompt, char[] choices, int numChoices)


But, you're in C++ so you should use a std::vector and then don't pass in numChoices, like this:

char ConsoleIO::GetNextChar(string prompt, std::vector const& choices)


Also, you have a bug. You aren't ever deleteing buffer, which means it's leaking.

Code Snippets

char ConsoleIO::GetNextChar(string prompt, char[] choices, int numChoices)
char ConsoleIO::GetNextChar(string prompt, std::vector<char> const& choices)

Context

StackExchange Code Review Q#113004, answer score: 5

Revisions (0)

No revisions yet.