Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
Jonathan Mee Avatar asked Sep 29 '25 09:09

Jonathan Mee


2 Answers

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
like image 71
Sergey Kalinichenko Avatar answered Oct 02 '25 06:10

Sergey Kalinichenko


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.

like image 24
Bo Persson Avatar answered Oct 02 '25 06:10

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!