Search code examples
cpointerscharheader-files

what's the use of "?" and ":" in a function that has a pointer as argument?


Today my teacher was teaching us how we could use pointers in C to simulate some common functions of this programming language, one of his examples was the rev_string function (shown below) which was created to simulate original strrev() from the <string.h> header.

void rev_string(char *s)
{
    char *t;
    int counter = 0, middle, temp, i, j, last, begin;

    for (t = s; *t != '\0'; t++)
        counter++;

    middle = (counter % 2 == 0) ? (counter / 2) : ((counter - 1) / 2);
    j = counter - 1;
    for (i = 0; i < middle; i++)
    {
        last = s[j];
        begin = s[i];
        temp = last;
        s[j] = begin;
        s[i] = temp;
        j--;
    }
}

After looking at the code above several times, I could not figured out the the use of ? and : declared inside the middle variable. Could anyone explain me why are those symbols necessary in the code above?


Solution

  • This is the conditional operator. It is a ternary operator which takes the form "condition ? if-part : else-part".

    It evaluates its first part. If the result is non-zero, the second part is evaluated and becomes the result of the expression, otherwise the third part is evaluated and becomes the result of the expression.

    So this:

    middle = (counter % 2 == 0) ? (counter / 2) : ((counter - 1) / 2);
    

    Is equivalent to:

    if (counter % 2 == 0) {
        middle = (counter / 2);
    } else {
        middle = ((counter - 1) / 2);
    }