C code - a way to convert 5 to 7 and 7 to 5 without "if"

I want to write a function that gets a number X and if X=5 it returns 7 , if X=7 it return 5 otherwise, return something else. There is the trivial way - to use "if" blocks Another way - to use a map (5 mapped to 7, 7 mapped to 5) Third way - to write the matching linear mathematical equation BUT I'm looking for the 4th way of doing it (again - without using "if" blocks at all).

It feels like I need to use bit operation but I'm not dominant in this area so I need help.

Any ideas?



int fun(int p)
    return p^2;

As well as the obvious bitwise XOR solution, you can also exploit the fact that a boolean expression returns 1 or 0, e.g.

int f(int x)
    return (x == 5) * 7 + (x == 7) * 5;

and there are other simple arithmetic methods, e.g.

int f(int x)
    return 12 - x;

I hope this is no homework I do for you:

int mysteriousFunction( int x ) {
    return (x ^ 2);

if input range is bounded and small, use input as index into a lookup table of results...

Need Your Help

Using JavaFX in a Netbeans Platform application

java javafx javafx-2 netbeans-platform

I tried to start developing an NB platform application that holds a JFXPanel in a TopComponent. Unfortunately, an Exception is thrown at runtime when the JFXPanel is instantiated. I saw that it's b...

How to make a rails template forcefully not run bundle install after rails new is finished?

ruby-on-rails ruby bundler generator ruby-on-rails-3.2

I am creating a Rails Template with stuff I want to do, including setting up a RVM gemset and installing gems inside it. I can do this just fine programmatically, but I also would like to disable the