PTR_IF(9)

πŸ“¦ version 7.3.1, in nixpkgs unstable

πŸ’œ PTR_IF(9) β€” from the Kernel API Manual, bestie

okay so picture this: a tiny macro in PTR_IF(9) that's literally just doing a vibe check on your conditional and handing you back either a pointer or NULL. that's it, that's the whole girlie. she's small, she's iconic, she's the main character of conditional compilation. πŸŽ€


✨ NAME ✨

PTR_IF β€” evaluates to @ptr if @cond is true, or to NULL otherwise. no cap, that's exactly what she does. πŸ’…


🌸 SYNOPSIS 🌸

PTR_IF (cond , ptr );

πŸ¦‹ ARGUMENTS πŸ¦‹

  • cond β€” a conditional, usually in a form of IS_ENABLED(CONFIG_FOO). like, that's the typical glow-up situation she finds herself in. ✨
  • ptr β€” a pointer to assign if cond is true.

πŸ’– DESCRIPTION πŸ’–

so PTR_IF(IS_ENABLED(CONFIG_FOO), ptr) evaluates to ptr if CONFIG_FOO is set to 'y' or 'm', or to NULL otherwise. and heads up bestie: the ptr argument must be a pointer. that's non-negotiable, it's giving strict. πŸ™ˆ

the macro can be very useful to help the compiler drop dead code. like, genuinely obsessed with how much she eats in that department. πŸ”₯

for instance, consider the following:

#ifdef CONFIG_FOO_SUSPEND
static int foo_suspend(struct device *dev)
{
   ...
}
#endif

static struct pm_ops foo_ops = {
#ifdef CONFIG_FOO_SUSPEND
    .suspend = foo_suspend,
#endif
};

while this works, the foo_suspend macro is compiled conditionally, only when CONFIG_FOO_SUSPEND is set. and that's... kind of problematic, ngl 😭 because there could be a build bug in this function, and we wouldn't have a way to know unless the configuration option is set. like the bug is just sitting there, unbothered, invisible to CI. πŸ’€

an alternative is to declare foo_suspend always, but mark it as __maybe_unused. this works, but the __maybe_unused attribute is required to instruct the compiler that the function may not be referenced anywhere, and is safe to remove without making a fuss about it. so basically it makes the programmer responsible for tagging the functions that can be garbage-collected. you're the one doing the labelling bestie, the compiler isn't gonna guess. 🫢

with the macro it is possible to write the following:

static int foo_suspend(struct device *dev)
{
   ...
}

static struct pm_ops foo_ops = {
    .suspend = PTR_IF(IS_ENABLED(CONFIG_FOO_SUSPEND), foo_suspend),
};

and the foo_suspend function will now be automatically dropped by the compiler, and it does not require any specific attribute. πŸ§šβ€β™€οΈβœ¨ she just handles it. no manual tagging, no fuss, no crumbs left behind. periodt. πŸ‘‘


πŸŽ€ SEE ALSO πŸŽ€

go read them, they're all lowkey serving. iykyk. 🌈


okay that's the whole page!! πŸ’œ this little love letter lives in ./include/linux and it's dated October 2026 β€” so like, future icon behavior honestly. byeee, go build something and let the compiler eat the dead code for you πŸ’…βœ¨πŸ“

πŸ“¦ where this page comes from