i kow c up to a good level but i have question for which i am anable to find solution that is to find greatest of 2 numbers in 'c' without using 'if' condition can any one help me out

Dani AI

Generated

A follow-up that ties together 's conditional approach and 's interest in bitwise tricks: the simplest, clearest solution is the conditional expression (already suggested), but if an explicit branch must be avoided you can use branchless masks or the standard math helpers (for floating point). Below are compact, widely used options and the portability caveats to watch for.

A common branchless trick for unsigned integers builds a mask from the comparison and picks bits from one operand or the other:

unsigned int max_u(unsigned int a, unsigned int b) {
    unsigned int mask = -(unsigned int)(a < b);   /* 0x0 or 0xFFFFFFFF... */
    return b ^ ((a ^ b) & mask);
}

This produces the larger value without an if and without an explicit conditional operator. It relies only on well-defined unsigned arithmetic and bitwise ops, so it is the safest bitwise approach for integers.

For floating-point values, use the standard library helpers instead of bit hacks:

#include <math.h>

double max_d(double a, double b) {
    return fmax(a, b);
}

Cautions: bit-twiddling for signed ints can invoke implementation-defined behavior (signed right shifts, signed overflow, or representation assumptions). The unsigned-mask trick above avoids most UB, but other tricks rely on twos-complement and arithmetic-shift behavior; avoid them if portability matters. For floating point use the fmax family (see cppreference for details). For background on representation assumptions see the two's-complement discussion. In most code the conditional expression is simplest and clearest; use branchless code only when profiling shows a real need.

References: fmax (C standard helper) — https://en.cppreference.com/w/c/numeric/math/fmax
Two's complement (representation caveats) — https://en.wikipedia.org/wiki/Two%27s_complement

Recommended Answers

All 3 Replies

Ternary operator perhaps ?

int a = 1;
int b = 2;

int c = ((a > b) ? a : b )

thanks

Is there any other way (I mean using bitwise operators) ???

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.