m69 m69 - 10 months ago 45
C Question

Shorthand for assignment if zero, like c = str[i] || 'x'

(This is a very basic question, but I can't seem to find an answer because it involves

, which is a problematic search term.)

Since a char can be interpreted as a boolean in a conditional like this:

if (str[i]) ...
if (c) ...

where '\0' is considered falsey and any other character is truthy, I was expecting this to work too:

char c = str[i] || 'x';

but it's always giving a value of 1. Is there a simple shorthand in C for this? I've become used to it in JavaScript, and I find it clear and concise.


You should handle it like any other abstraction, and write a function for it:

char non_zero_or_default(const char c, const char d)
    return c ? c : d;

then use it as:

char c = non_zero_or_default(str[i++], 'x');

You can inline it if you're worried about overhead.