Search code examples
ccode-snippets

How to interpret Nested Conditional Operator


i'm looking at part of an algorithm, and most of my c knowledge comes from knowing java. i understand that this is a conditional, but what exactly is the order of execution here/what's happening step by step? Thanks!

    int i, j, k;
    int *x = malloc(n * sizeof (int));
    for (i = 0, j = m, k = 0; k < n; k++) {
        x[k] = j == n      ? a[i++]
             : i == m      ? a[j++]
             : a[j] < a[i] ? a[j++]
             :               a[i++];
    }
    free(x);

Solution

  • It is equivalent to:

        for (i = 0, j = m, k = 0; k < n; k++) {
            if (j == n) x[k] = a[i++];
            else if (i == m) x[k] = a[j++];
            else if (a[j] < a[i]) x[k] = a[j++];
            else x[k] = a[i++];
        }