# In HLSL, what is the difference between "static const" and "#define" for constants?

So far I've been declaring all my constant variables as static const in my HLSL code, yet virtually every single shader example I've come across uses #define instead.

I know the reasons I would I use static const in C++ over the preprocessor and I just carried it into HLSL as well. However, I'm curious if there are any side effects or pros/cons to this, besides the standard C++ "static const versus #define" arguments.

It basically doesn't matter.

#define uses token-pasting to insert the specified value into the shader code whereever it occurs; the shader itself will see the token as if you simply hard-coded it at every occurrence instead.

A static const variable in, in actuality, a variable. Specifically, it is a variable that is initialized once, whose value persists between function calls, and which cannot be changed. Being a variable, can have the same things that all other variables can have: additional storage and type specifiers (precise), more complex types (such as float4), semantics and register assignments (see here for all the things). However, specifically for static const variables, most of those extras aren't allowed or don't apply (particularly since a global static is not visible to the application code).

The static const version may allow some compiler optimizations (minor ones), especially if the type of the variable is more complex (such as a float4 or matrix type), but that seems unlikely to matter much.

In the end, choose the one you prefer stylistically.

• Is there a reason why one would prefer static const to const? Are there optimizations specific to static const that won't apply to const? That is assuming the assigned value itself is just a constant. Apr 20 '17 at 19:40
• A static const local variable is initialized only once, but a regular const would presumably be initialized every time. You'd want a non-static const if the initialization is going to be dependent on parameters to the function, for example. Other than that I don't think there's anything special the optimizer will do.
– user1430
Apr 20 '17 at 20:19
• Thanks. I am seeing cases like static const float something = 1.53; for example, which shouldn't then make a difference with or without static. Apr 20 '17 at 21:30