about warning "cannot optimize loop, the loop counter may overflow"

Ian Lance Taylor iant@google.com
Thu May 19 00:35:00 GMT 2011


Jędrzej Dudkiewicz <jedrzej.dudkiewicz@gmail.com> writes:

> I have the following code:
>
> static const std::string paths[] = { "file1", "file2", "file2" };
> for (size_t i = 0; i < (sizeof(paths) / sizeof(paths[0])); ++i)
> {
>     if (access(paths[i], F_OK | R_OK) == 0)
>     {
>         return std::string(paths[i]);
>     }
> }
>
> It results in error:
>
> error: cannot optimize loop, the loop counter may overflow
> [-Werror=unsafe-loop-optimizations]
>
> (well, warning turned to error with -Werror) in the line "for (size_t i = ...".
>
> Changing "std::string" in array's declaration into "char* const"
> removes the warning (error). Why is that? I thought that this warning
> comes from optimizer, which knows the exact size of "std::string"
> object?

I'm not sure it's ever a good idea to use -Werror with
-Wunsafe-loop-optimizations.

I think you'll find that the error is not on the loop you are looking
at.  It's on the loop which initializes the static paths variable.  Or,
more accurately, it's on the loop which destroys the variable if some
exception is raised while initializing it.  That loop can not be
determined because it only destroys the objects which were in fact
initialized.  And that situation is evidently complex enough to confuse
the loop optimizer.

Ian



More information about the Gcc-help mailing list