I'm not sure if the following code can cause redundant calculations, or is it compiler-specific?
for (int i = 0; i < strlen(ss); ++i)
{
// blabla
}
Will strlen()
be calculated every time when i
increases?
I'm not sure if the following code can cause redundant calculations, or is it compiler-specific?
for (int i = 0; i < strlen(ss); ++i)
{
// blabla
}
Will strlen()
be calculated every time when i
increases?
Yes,
strlen(ss)
will be calculated every time the code runs.Yes. strlen will be calculated everytime when i increases.
If you didn't change ss with in the loop means it won't affect logic otherwise it will affect.
It is safer to use following code.
well, I noticed that someone is saying that it is optimized by default by any "clever" modern compiler. By the way look at results without optimization. I tried:
Minimal C code:
My compiler: g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Command for generation of assembly code: g++ -S -masm=intel test.cpp
Not common nowadays but 20 years ago on 16 bit platforms, I'd recommend this:
Even if your compiler isn't very smart in optimization, the above code can result in good assembly code yet.
We can easily test it :
Loop condition evaluates after each repetition, before restarting the loop .
Also be careful about the type you use to handle length of strings . it should be
size_t
which has been defined asunsigned int
in stdio. comparing and casting it toint
might cause some serious vulnerability issue.Yes, the
strlen(ss)
will calculate the length at each iteration. If you are increasing thess
by some way and also increasing thei
; there would be infinite loop.