Jonathan Mee
Jonathan Mee

Reputation: 38919

Is strlen Optimized out for String Literals?

So say that I have this:

const auto foo = "lorem ipsum"

If I use strlen(foo) in my code, is the 11 found at run time or is that injected at compile time?

Upvotes: 4

Views: 1765

Answers (3)

Bo Persson
Bo Persson

Reputation: 92211

The standard doesn't allow implementations to add constexpr, except where it is explicitly required:

[constexpr.functions]
This document explicitly requires that certain standard library functions are constexpr ([dcl.constexpr]). An implementation shall not declare any standard library function signature as constexpr except for those where it is explicitly required.

So strlen is out of bounds.

However, to support constexpr constructors of string_view, the C++17 standard requires that certain members of char_traits, like char_traits::length, are constexpr anyway.

And this month we have had new compiler releases of gcc 8.1 and MSVC 15.7 so that the latest versions of the major compilers now all implement char_traits::length as constexpr.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

The answer depends on the compiler and the current optimization level.

A quick experiment with this C++ code

#include <cstring>
int strlen_of_const() {
    return strlen("lorem ipsum");
}

on compiler explorer reveals, that some compilers would optimize out the call, while other compilers would make the call at runtime. For example, gcc optimizes out the call:

strlen_of_const():
  mov eax, 11
  ret

MSVC, on the other hand, keeps the call:

$SG3533 DB        'lorem ipsum', 00H
EXTRN   strlen:PROC
strlen_of_const PROC
        sub      rsp, 40              ; 00000028H
        lea      rcx, OFFSET FLAT:$SG3533
        call     strlen
        add      rsp, 40              ; 00000028H
        ret      0
strlen_of_const ENDP

Upvotes: 5

Jesper Juhl
Jesper Juhl

Reputation: 31447

It depends entirely on your compiler and whether or not you are building with optimizations enabled.

A good modern compiler is likely to optimize the strlen away and produce 11 as a constant when optimizing, but nothing in the language forces it to. So it's also perfectly valid for the compiler to generate a function call.

You just have to test with your compiler of choice at your optimization level of choice and read the generated assembly.

Upvotes: 2

Related Questions