Aioi Yuuko
Aioi Yuuko

Reputation: 118

Can't add to a string literal in C to shift its index

I was code-golfing the famous "fizzbuzz" screening question in C (The point of this question is understanding how C operators work, not code golf; don't vote me off topic ^^"), and I came up with this line:

puts(&"Fizz\0FizzBuzz"[i%15?i%3?9:0:5]));

Which seems a little unnecessary to me because I thought I could just do:

puts("Fizz\0FizzBuzz"+i%15?i%3?9:0:5));

but that segfaults on the first would-be Fizz. My question is: why can't I index a string literal by simply adding to it? I've tried casting the addend to size_t, but that does nothing useful. Given that for an arbitrary char *p (or a pointer to any type for that matter), p[n]is just syntactic sugar for (*p+n), and (I think) &*p == p.

Why, then, is &p[n] != p+n?

EDIT: Turns out I was just catching Fizz\0FizzBuzz"+i%15 in my ?:. Damned operator precedence. I'm a moron. :)

Upvotes: 1

Views: 30

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

The problem your code is that you are missing parentheses. This works perfectly fine:

puts("Fizz\0FizzBuzz"+(i%15?i%3?9:0:5));

In your original code the condition of the first ? : operator is

"Fizz\0FizzBuzz"+i%15

which is not what you intended.

Demo.

Upvotes: 2

Related Questions