Is conditional macro code optimized?

If one of the rust macro arguments takes a boolean constant as argument and expands if/then/else code
base on that boolean constant, does the expanded code annd condition check get optimized based on the macro argument?

For example , if I had the following macro definition and invocaton as below.

Will the compiled code still have code to check if true ? Or will it be optimized out?

macro_rules! condcode {
    ( $x:expr  ) => {
        {
            if $x {
                  something if true;
            } else {
                   something if false;
            }
        }
    };
}

condcode!(true);

Macro doesn't do anything about such optimization. Macro will be expanded into code you've provided.

Code below doesn't generates conditional opcodes, the generated binary doesn't even include the "FALSE" string data.

fn with_cond(cond: bool) {
    if cond {
        println!("TRUE")
    } else {
        println!("FALSE")
    }
}

pub fn unconditional() {
    with_cond(true)
}
1 Like

Your example macro with true as an argument will cause the compiler to optimize away the conditional branch 100% of the time (unless you disable optimizations) ¹.

¹ See alice's response below

You can't fully disable optimizations. Even the lowest optimization level optimizes the else branch away here:

pub fn without_cond() {
    if true {
        println!("TRUE")
    } else {
        println!("FALSE")
    }
}
2 Likes

Thanks. It would be helpful to clarify this with examples in the rust documentation with examples under the macro section

I was looking for something like #if-else in C In rust macros

Looks like I don’t need it to achieve what I want.

Thanks for the explanation

As already mentioned before, this has nothing to do with macros. All runtime code is optimized equally by LLVM, whether or not it originates from a macro expansion.

If you want proper conditional compilation, the #[cfg], #[cfg_attr] or cfg!() macros should be used, as described in the relevant part of the Book.

1 Like

I got that.
I had to come here and ask this question here because I couldn’t find the information I needed in the rust documentation.

Hence my suggestion to leave a note in the macro documentation about this optimization with an example readers understand this