0

This code makes an ASCII representation of a Sierpinski triangle of order 4, and I have no idea how the last printf works. If anyone can explain it to me, I would be very grateful.

#include <stdio.h>

#define SIZE (1 << 4)
int main()
{
    int x, y, i;
    for (y = SIZE - 1; y >= 0; y--, putchar('\n')) {
        for (i = 0; i < y; i++) putchar(' ');
        for (x = 0; x + y < SIZE; x++)
            printf((x & y) ? "  " : "* ");
    }
    return 0;
}
2
  • 2
    Which part of it don't you understand? Do you know what the & operator does? Do you know the ? : conditional operator? Break it down into pieces and it should become clear. Commented Apr 19, 2018 at 23:46
  • If (x & y) evaluates to true, it prints a " ", otherwise a "* ". Commented Apr 19, 2018 at 23:54

2 Answers 2

1

The ? is a ternary operator. It evaluates the expression on the left, and if it's non-zero (true) it selects the first value before the colon : and if it's zero (false) it selects the second.

Sign up to request clarification or add additional context in comments.

Comments

1

printf((x & y) ? " " : "* "); is more or less equivalent to:

if ((x & y) != 0) {
    printf("  ");
}
else {
    printf("* ");
}

2 Comments

"more or less"? I'd say it's exactly equivalent. I resisted posting an almost identical answer.
I've gotten into the habit of saying "more or less" in answers like this because there's often some detail that's not important to the question/answer but is technically different. It's a CYA that I just use without too much thought.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.