Broken code when using std::clamp with no compiler warning

I wrote some generic C++ code I wanted to use from a CUDA kernel and happened to use std::clamp in this function. My code compiled and ran, but with incorrect results.

Once I copy-pasted the helper function body into the kernel, I then got an error message. error: calling a constexpr hostfunction("clamp") from aglobal function("myKernel") is not allowed. The experimental flag '--expt-relaxed-constexpr' can be used to allow this.

Using my own implementation of clamp everything is fine.

Should I be getting the same error when calling my helper function or what? How can I avoid this situation?

if you want to use C++ standard library functionalities in CUDA, the right path is to use CCCL

#include <cuda/std/algorithm.clamp.h>

__device__ auto f(auto v) {
    return cuda::std::clamp(v, INT8_MIN, INT8_MAX);
}

Yeah, this exact trap bit me once too. The silent misbehavior is the scary part. What’s happening is the device compiler checks the constexpr call only where it can actually see it. When clamp was tucked inside your plain helper function, the device-side compilation never flagged the call, so your kernel just ran with silently wrong results. The moment you inlined the helper body into the kernel, the check fired and you finally got the error. So yes, you should have gotten the error both times, but the compiler’s dual host/device compilation makes that check inconsistent depending on where the call is visible.

My rule now is to never let std:: algorithms into anything a kernel can reach. I keep a tiny header of my own host device clamp/min/max helpers and use those everywhere instead, then there is zero ambiguity about which version the device compiler grabbed. For anything bigger, CCCL’s cuda::std versions are the way to go like fbusato said.

Practical debugging tip for the future: if you ever see correct results on the host side but wrong results on device with zero warnings, suspect exactly this. Comparing the generated PTX before and after changing a suspicious call usually reveals whether the device compiler actually emitted what you expected.