[英]Does gcc automatically perform a mathematical operations on const values during compilation
Lets say we perform 可以说我们表演
malloc(4 * sizeof(int))
Now, the number 4 is a constant and from my understanding sizeof
is actually compile time function (unless you have a variable inside of it). 现在,数字4是一个常数,根据我的理解,
sizeof
实际上是编译时间函数(除非您内部有变量)。
In this case (considering x86) sizeof(int)
would also be 4. My question is: will the gcc optimization perform the calculation itself or will the equation be generated in the asm? 在这种情况下(考虑x86),
sizeof(int)
也将为4。我的问题是:gcc优化将自行执行计算还是将在asm中生成方程式?
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
. 我们可以使用
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
Ie the only constants you see in there are 16
( 4 * sizeof(int)
), and 0
(the implicit return value from main()
). 即,您看到的唯一常量是
16
( 4 * sizeof(int)
)和0
( 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. 请注意,在C语言中有一类称为“整数常量表达式”的表达式,应该在编译时进行评估。 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. 您可以使用
4 * sizeof(int)
作为数组的大小-甚至在_Static_assert
子句中-自然地,则必须在编译期间对其进行求值,但是在一般情况下,例如此处,C标准不需要另一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.