Skip to content

Instantly share code, notes, and snippets.

@tfc
Created February 20, 2016 20:14
Show Gist options
  • Save tfc/4678e733cdfecffaf11a to your computer and use it in GitHub Desktop.
Save tfc/4678e733cdfecffaf11a to your computer and use it in GitHub Desktop.
__SHORT_FILE__ Macro
#include <stdio.h>
using cstr = const char * const;
static cstr constexpr past_last_slash(cstr str, cstr last_slash)
{
return
*str == '\0' ? last_slash :
*str == '/' ? past_last_slash(str + 1, str + 1)
: past_last_slash(str + 1, last_slash);
}
static cstr constexpr past_last_slash(cstr str) { return past_last_slash(str, str); }
#define __SHORT_FILE__ ({constexpr cstr sf__ {past_last_slash(__FILE__)}; sf__;})
int main()
{
puts(__SHORT_FILE__);
return 0;
}
@mbehr1
Copy link

mbehr1 commented Dec 15, 2019

btw, I noticed that constexpr functions allow loops as well. so the recursion can be avoided easily:

static constexpr const char* past_last_slash_loop(const char * const str)
{
  const char* last_slash = str;
  for (const char* pos = str; *pos != 0x0; ++pos) {
    if (*pos == '/')
      last_slash = pos + 1;
  }
  return last_slash;
}

this should(tm) speedup compilation in larger projects. or?

@tfc
Copy link
Author

tfc commented Dec 15, 2019

Hey @mbehr1, you are right with loops being allowed since C++14 i think, but this piece of code was designed to be run on c++11 compilers also. I don't think that loop vs. recursion (this is easily tail-recursionable) is a speed difference, but i also did not measure it. I guess it remains a matter of taste.

@mbehr1
Copy link

mbehr1 commented Dec 15, 2019

ah. right. that's c++14 only. and yes, more a matter of style

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment