V
V
Viktor2016-01-25 08:05:53
C++ / C#
Viktor, 2016-01-25 08:05:53

Will the value of strlen("str") be evaluated at compile time or at runtime?

Will the code after compilation

int len = strlen("str");
int a = len + 1;
int b = len + 2;

equivalent to code
int a =  strlen("str") + 1;
int b =  strlen("str") + 2;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Antony, 2016-01-25
@Levhav

Absolutely not. But, if the compiler considers that your string does not change (and it does), it can optimize this code by replacing it with a constant. By the way, he can also throw out len, replacing it with a constant in the expressions below.
It is possible to say that it will surely replace only by knowing exactly which compiler is used and the compilation options.
gcc with -O3 100% will throw this line out and replace the expressions for a and b with a constant, but with -O0 it will most likely not touch it.
To make sure that the compiler does not optimize anything, you can use volatile, but in most cases there is no reason for this.

R
res2001, 2016-01-25
@res2001

Unlikely.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question