if Statement

Conditionally execute a series of statements, based on the evaluation of the conditional expression.

[Attribute] if ( Conditional )

{

  Statement Block;

}

 

Parameters

Attribute

An optional parameter that controls how the statement is compiled.

AttributeDescription
branchEvaluate only one side of the if statement depending on the given condition.
Note  When you use Shader Model 2.x or Shader Model 3.0, each time you use dynamic branching you consume resources. So, if you use dynamic branching excessively when you target these profiles, you can receive compilation errors.
 
flattenEvaluate both sides of the if statement and choose between the two resulting values.

 

Conditional

A conditional expression. The expression is evaluated, and if true, the statement block is executed.

Statement Block

One or more HLSL statements.

Remarks

When the compiler uses the branch method for compiling an if statement it will generate code that will evaluate only one side of the if statement depending on the given condition. For example, in the if statement:


[branch] if(x)
{
    x = sqrt(x);
}

The if statement has an implicit else block, which is equivalent to x = x. Because we have told the compiler to use the branch method with the preceding branch attribute, the compiled code will evaluate x and execute only the side that should be executed; if x is zero, then it will execute the else side, and if it is non-zero it will execute the then side.

Conversely, if the flatten attribute is used, then the compiled code will evaluate both sides of the if statement and choose between the two resulting values using the original value of x. Here is an example of a usage of the flatten attribute:


[flatten] if(x)
{
    x = sqrt(x);
}

There are certain cases where using the branch or flatten attributes may generate a compile error. The branch attribute may fail if either side of the if statement contains a gradient function, such as tex2D. The flatten attribute may fail if either side of the if statement contains a stream append statement or any other statement that has side-effects.

An if statement can also use an optional else block. If the if expression is true, the code in the statement block associated with the if statement is processed. Otherwise, the statement block associated with the optional else block is processed.

See also

Flow Control

 

 

Show: