Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary expression which "does nothing" (noop) if the condition is false?

Out of curiosity I started wondering if it's possible to have a ternary expression that, if it evaluates to false, does nothing in the false branch.

Ie is there a way to write something like this:

variable = (someBool) ? i : <do nothing>;

As opposed to:

if (someBool) {
    variable = i;
}

I tried ((void)0) or while(false){}; as no-op but the compiler expects an expression.

UPDATE:

I realized the question lost some meaning because I tried to make the code easier. The initial idea I had was to initialize a static var with a ternary - using the static var itself as the condition:

static int var = (var != 0) ? var = 1 : (var already initialized, do nothing);

This is assuming that uninitialized variables are initialized to 0 which is not always true (or never in release builds, not quite sure). So maybe it's a hypothetical question.

like image 947
LearnCocos2D Avatar asked Oct 08 '13 10:10

LearnCocos2D


2 Answers

how about short-circuit?

int variable = 0;
bool cond = true; // or false

(cond && (variable = 42));

printf("%d\n", variable);
like image 96
none Avatar answered Sep 19 '22 13:09

none


How about this:

variable = (someBool) ? i : variable ;

Though I would personally prefer the original if statement

like image 36
musefan Avatar answered Sep 19 '22 13:09

musefan