libcs50 icon indicating copy to clipboard operation
libcs50 copied to clipboard

Possibly unnecessarily complicated va_start/va_end in get_double

Open rillig opened this issue 5 years ago • 0 comments

The implementation of get_double and the similar functions initializes the va_list ap at the beginning of the function and cleans it up before each return statement. This seems unnecessarily complicated and error-prone. (The current implementation is fine, it just has potential to become erroneous.)

A simpler way would be:

while (true)
{
    // Get line of text
    va_list ap;
    va_start(ap, format);
    string line = get_string(&ap, format);
    va_end(ap);

    // Return DBL_MAX on failure
    if (line == NULL)
    {
        return DBL_MAX;
    }

This code has the benefit of making the actual scope of ap smaller than before, and of pairing the va_start with the va_end in an obvious way.

Is there a compelling reason for the current implementation?

rillig avatar Aug 19 '19 17:08 rillig