Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewriting a piece of C code without conditional statements or operators?

Tags:

c

I was in a technical interview where the interviewer gave me a piece of code like this

  int a=1;
  a++;
  ...something..
  ...something.
  if(a==25)
   a=0;

he said me to rewrite this code without using switch,if else or ternary operator for the if condition. How it can be done?

like image 548
mrigendra Avatar asked Sep 16 '13 08:09

mrigendra


People also ask

How do you write codes without an if statement?

i.e. you could just as easily write bool isSmall = i < 10; - it's this that avoids the if statement, not the separate function. Code of the form if (test) { x = true; } else { x = false; } or if (test) { return true; } else { return false; } is always silly; just use x = test or return test .

What conditional operator can you use to replace the if-else statement in C?

The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .

What can I use instead of if-else?

The conditional operator (or Ternary operator) is an alternative for 'if else statement'.


1 Answers

It's quite simple actually:

a *= (a != 25);

This will multiply a by 0 if a is equal to 25, else it will multiply a by 1.

If you're also not allowed to test for equality then here is a fully arithmetic way:

unsigned int v = a - 25;

/* test for bits set and put result in lsb of v */
v |= v >> 16;
v |= v >> 8;
v |= v >> 4;
v |= v >> 2;
v |= v >> 1;

/* set a to a if lsb of v is 1, else set to 0 */
a *= v & 1;
like image 122
orlp Avatar answered Oct 08 '22 06:10

orlp