How do you program a If-sentence without actually using it?

In many programming languages, 'if' syntax is provided as the primary means of conditional branching. It doesn't really make sense to define an 'if' function inside the language if it's already given to you by the language.

In the spirit of the question, however, you could replace each 'if' statement with a loop in many imperative languages, but this serves little purpose but for obfuscation. For example, you could replace an 'if' statement with a 'for' loop which will execute at most once.

// this if statement...
if (someBoolean)
{
    DoThings();
}

// ... is equivalent to this for loop
for (int i = 0 ; someBoolean && i < 1 ; i++)
{
    DoThings();
}

What I think you're really asking is how imperative languages compile the high-level 'if' statements to low-level machine code. This usually relies on a special machine instruction called a JUMP which moves the program counter (a special value which saves your place within a program's execution) to another specified memory location. JUMPs have conditional variants, such as JUMPZ which will only move the program counter if some value equals 0, otherwise not changing the program state.

To compile an 'if' statement to a sequence of machine instructions, you would first provide instructions to evaluate the boolean condition, and then follow it with a JUMPZ instruction, then the code to execute the body of the 'if', then the target of the JUMPZ instruction. The boolean would be evaluated, and if it results in false (treating 0 as false, and any other value as true), the JUMPZ instruction would skip over the body of the 'if' to some memory location afterwards. If the boolean results in true, the jump is not taken, and the program flow naturally falls into the body of the 'if'.

/r/askscience Thread