Testing if an expression has side effects at compile time

Alejandro Colomar alx@kernel.org
Fri Jan 9 12:07:34 GMT 2026


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>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc/attachments/20260109/15702f48/attachment.sig>


More information about the Gcc mailing list