Flame
Flame

Reputation: 2207

Does a function local static variable prevent function inlining?

I'm writing an attribute shim to get the raw c-string from a library's string implementation. This specific string class, say string_t has members length() and data(). When length() == 0 data() == nullptr.

Now I am using an api that doesn't like null strings so my shim returns the address of an empty string.

inline char const* get_safe_c_str( string_t const& str ){
    static char const empty[] = "";
    return str.length() > 0 ? str.data() : ∅
}

Does my static variable prevent the compiler from inlining this function?

Upvotes: 2

Views: 229

Answers (1)

James McNellis
James McNellis

Reputation: 355267

No, it does not prevent inlining. There will still be only one instance of the function-local static variable, and everywhere the function is expanded inline, that instance will be used.

Whether a particular compiler with particular options actually inlines such a function is another matter, and you'd have to compile your program to see what your compiler actually does, but there is no technical reason the function can't be inlined.

Note, however, that in your program, return str.length() > 0 ? str.data() : ""; would also work fine; a string literal has static storage duration and exists until the program terminates.

Upvotes: 4

Related Questions