This is called "constant-folding" and yes, it will happen before assembly. Assembly in itself is usually not optimized at all.
Consider the minimal program
#include <stdlib.h>
int main(void)
{
malloc(4 * sizeof(int));
}
We can compile it into assembly with gcc -S
. On my computer, the resulting assembly says:
main:
pushq %rbp
movq %rsp, %rbp
movl $16, %edi
call malloc@PLT
movl $0, %eax
popq %rbp
ret
I.e. the only constants you see in there are 16
(4 * sizeof(int)
), and 0
(the implicit return value from main()
).
Note that in C there is a class of expressions that are called "integer constant expressions" that are supposed to be evaluated at the compilation time. You can use 4 * sizeof(int)
as the size of an array - or even within a _Static_assert
clause - naturally then it must be evaluated during the compilation, but in general case, such as here, the C standard does not require one or the other.