Home > Backend Development > C++ > Why Doesn't `if constexpr` Work as Expected in Non-Templated C Functions?

Why Doesn't `if constexpr` Work as Expected in Non-Templated C Functions?

Susan Sarandon
Release: 2024-11-06 10:54:02
Original
580 people have browsed it

Why Doesn't `if constexpr` Work as Expected in Non-Templated C   Functions?

if constexpr in C 17 Not Working in Non-Templated Functions

Introduction

The C 17 standard introduced the if constexpr construct, which allows for conditional execution based on constant expressions. However, it has been observed that if constexpr behavior differs when used in templated versus non-templated functions.

Problem

Consider the following non-templated function:

<code class="cpp">void print()
{
  auto value = 100;
  if constexpr (std::is_pointer_v<decltype(value)>){
    std::cout << "Ptr to " << *value << std::endl; // Error
  }
  else {
    std::cout << "Ref to " << value << std::endl;
  }
}</code>
Copy after login

This code results in a compilation error because *value is invalid for the deduced type int.

Answer

This behavior is by design. In templated functions, if constexpr can avoid instantiating branches that are not valid for specific template specializations. However, in non-templated functions, if constexpr does not suppress compilation of the non-taken branch.

Both branches of the if constexpr statement are parsed and analyzed, even if the branch not taken is invalid. Therefore, in the above code, the compiler will attempt to evaluate *value for an int type, resulting in an error.

Conclusion

This distinction is important to understand when using if constexpr. In non-templated functions, it should only be used to check constant expressions that are guaranteed to be valid for all possible values of the input parameters.

The above is the detailed content of Why Doesn't `if constexpr` Work as Expected in Non-Templated C Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template