Hi!

I'm trying to find a way to verify that an expression (usually passed as
an argument to a macro) has no side effects.  Is this possible?

Let's say I want to implement strnul():

        #define strnulA(s)  (s + strlen(s))  // Problem: evaluates twice

        #define strnulB(s)        \
        ({                        \
                auto  s_ = s;     \
                s_ + strlen(s_);  \
        })

The problem with strnulB() is that it has a local variable 's_'.  This
means I can't pass an argument called s_.  That is, the following call
doesn't work:

        strnulB(s_);

Is there a way to implement something like this?:

        #define strnulC(s)                           \
        ({                                           \
                static_assert(!has_side_effects(s)); \
                s + strlen(s);                       \
        })

If there's no way, it would be interesting to add compound literals of
function type to achieve this:

        #define strnulD(...)                                          \
        ((static inline auto                                          \
          (auto s))                                                   \
        {                                                             \
                return s + strlen(s);                                 \
        }(__VA_ARGS__))

Which guarantees that the argument is evaluated once.


Have a lovely day!
Alex

-- 
<https://www.alejandro-colomar.es>

Attachment: signature.asc
Description: PGP signature

Reply via email to