简体   繁体   中英

C - Ternary operator

Why when I'm doing this:

int     ft_is_alpha(char *str, int i)
{
    return (((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) ? 0 : 1);
}

It crashing but, when I'm doing this:

int     ft_is_alpha(char *str, int i)
{
    if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
    {
        return (1);
    }

    return (0);
}

It doesn't crashing..
I call the function like this

for (i = 0; str[i] != '\0'; ++i)
    {
        if (ft_is_equal_to(str, i))
        {
            ++count;
            int     j;

            j = i - 1;
            while (str[++j] != '\0' && ft_is_alpha(str, j))
            {
                ++length;
            }
        }
    }

I don't know what you mean by crashing , the first function implements the test correctly but returns the opposite of the correct value. The branches of the ternary operator should be in the same order as in the if (cond) {} else {} statement. It should read:

int ft_is_alpha(char *str, int i) {
    return (((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) ? 1 : 0);
}

Since the condition already evaluates to a boolean, you can simplify the code by removing the unneeded ternary operator and some parentheses:

int ft_is_alpha(const char *str, int i) {
    return (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z');
}

Removing the last sets of parentheses can be done, but with less readability.

Note that str should be declared const char * as the string is not modified by the function. Also remove the parentheses in return (1); , they are not needed and considered bad style.

Furthermore, why not pass str[i] instead of str and i separately? This change of API would make the code much easier to read, faster to execute and safer to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM