C++ Zero time array count and strlen/strnlen.

So little C++ so much good!

[ Update 2021-03-18 ]

There was “a bug the size of the house” in there. strlen and strnlen do not count the end of string char. Of course. Godbolt code is here.Copy away.

[ 2017-10-19 ]

It is not me who first thought of this, but just today, I figured writing a “compile-time” aka “zero time” strlen() and strnlen() in modern C++ is actually possible and obvious. Not for pointers though. For arrays and for arrays of characters that is. If you haven’t from somewhere else copy-paste from here, at your pleasure. Perhaps you will find it a “proper” and tested modern C++ code.

Yes there are also dbj::strlen() and dbj::strnlen() to take proper care of char, wchar_t, char16_t and char32_t. Hint: char8_t avoid if you can.

Usage? If you need strlen() or strnlen() just use dbj::strlen() or dbj::strnlen(). In case you are passing arrays of characters the execution time is “zero”. Both are based on dbj::arrlen . Array length (aka count) includes '\0' char, where str(n)len does not.

For example:

All of the dbj:: calls above will take “zero” time to execute. That is: they are all compile-time. And whatever is the (legal) size of the arrays used, the execution time will be still “zero”.



What are then the real-time savings of using this? Yes, it is quite hard to compute., them real-time savings, if your app uses the code below.

It may be hard to measure but it is obvious there must be a time-saving. It depends on the compiler on the OS and on the number of static (char) arrays your application might contain.

This little “nugget” shows, perhaps dramatically, the advantages of using modern C++ compilers.

For more modern C++ speculations and more copy-paste opportunities, please click HERE .

Obviously, the whole idea is based on the count of a generic array of T. Above you have already spotted dbj::arrlen and dbj::arrnlen .  Obviously fully compile-time enabled.

There are various COUNT_OF macros as you might know about. But none of them is trivial and still, that is just C pre-proc mumbo jumbo. Here is an infinitely more clear solution.

The full source