Search code examples
csyntax

Is there an elegant way to check if multiple variables equal one value or vice versa


Is there a neater/shorter way to write out things like:

if(var1 == 1 && var2 == 1 && var3 == 1)

or

if(var1 == 1 || var1 == 4 || var1 == 6)

I know there's all sorts of commonly used syntax shortcuts that make things look a bit cleaner and I figured there may be some other way to write it that I don't know of considering how bulky it gets.


Solution

  • Is there an elegant way

    You can throw as many abstractions as you want, and it will just result in pilling up layers and more code to debug. Bottom line, the code you presented is completely fine, readable, clear, short and very elegant.

    The only thing I would do is remove magic number by declaring a variable with readable name. Like int this_is_important_number = 1; if (var1 == this_is_important_number && var2 == this_is_important_number && var3 == this_is_important_number).

    You can throw a macro at it:

    #define ALL_EQ_1(x, a)  ((x) == (a))
    #define ALL_EQ_2(x, a, ...)  ALL_EQ_1(x, a) && ALL_EQ_1(x, __VA_ARGS__)
    #define ALL_EQ_3(x, a, ...)  ALL_EQ_1(x, a) && ALL_EQ_2(x, __VA_ARGS__)
    #define ALL_EQ_N(_4,_3,_2,_1,N,...)  \
            ALL_EQ##N
    #define ALL_EQ(x, ...)  \
            (ALL_EQ_N(__VA_ARGS__,_4,_3,_2,_1)(x,__VA_ARGS__))
    int main() {
        int var1 = 1, var2 = 2, var3 = 3;
        return ALL_EQ(1, var1, var2, var3);
    }
    

    You can throw a variadic function at it:

    #include <stdarg.h>
    #include <stdbool.h>
    #include <limits.h>
    bool all_eq_INT_MAX_v(int to, va_list va) {
        while (1) {
            const int v = va_arg(va, int);
            if (v == INT_MAX) {
                break;
            }
            if (v != to) {
                return false;
            }
        }
        return true;
    }
    bool all_eq_INT_MAX(int to, ...) {
        va_list va;
        va_start(va, to);
        const bool r = all_eq_INT_MAX_v(to, va);
        va_end(va);
        return r;
    }
    #define all_eq(x, ...)  all_eq_INT_MAX(x, __VA_ARGS__, INT_MAX)
    
    int main() {
        int var1 = 1, var2 = 1, var3 = 1;
        return all_eq(1, var1, var2, var3);
    }
    

    Or any other abstraction. The problem, is that you have to then later maintain and debug such code, which is not worth it. A simple if statement is just great.