MISRA Discussion Forums
A7-1-2: Is it really intented to mark also functions as constexpr? - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: AUTOSAR C++:2014 rules (https://forum.misra.org.uk/forumdisplay.php?fid=185)
+--- Thread: A7-1-2: Is it really intented to mark also functions as constexpr? (/showthread.php?tid=1657)



A7-1-2: Is it really intented to mark also functions as constexpr? - cgpzs - 28-08-2023

Hi,

A7-1-2 says:
The constexpr specifier shall be used for values that can be determined at compile time.

So it only talks about "values", not "functions". However, in the example, it says the following code is not compliant, because the function Pow1 "can be" constexpr but is not marked as such:

Code:
std::int32_t Pow1(std::int32_t number)
{
    return (number * number);
}
void Fn()
{
    const std::int32_t threeSquare = Pow1(3); // Non-compliant, possible run-time evaluation
}

On the other hand, examples are not normative - the title of the rule is.

Therefore I ask: is rule A7-1-2 intended to mark every single function as constexpr if it _can_ be constexpr?

In my opinion, this has negative consequences. Constexpr-ness of a function should be a careful design decision, not something added blindly to comply with a static analysis tool. It limits the way an author can choose to implement a given function. Maybe today the function _can_ be constexpr, but tomorrow as an author I want to refactor the implementation to e.g. use more modern libraries from STL, which don't have constexpr support in C++14 (for example, a silly std::array::operator[] is not supported in constexpr functions). Changing the implementation would require removing constexpr and updating also all the clients (which could dramatically cascade into second-order functions and so on). Or the alternative would be to be locked into constexpr and have to resort to older-style code to implement it (e.g. use a C array instead of std::array), making the function ultimately less safe and violating other Autosar rules.

Thanks!


RE: A7-1-2: Is it really intented to mark also functions as constexpr? - misra cpp - 27-10-2023

It’s not the intention of this rule to force constexpr to be added to all functions who’s return value can be evaluated at compile time.

The example  const std::int32_t threeSquare = Pow1(3);  should be shown as compliant, because Pow1 has to be evaluated at run-time as its not constexpr.

However,  const std::int32_t  fourSquare = Pow2(4);    would be non-compliant, as Pow2 is declared constexpr, and Pow2(4) can be evaluated at compile-time, so foursquare can be declared constexpr.


RE: A7-1-2: Is it really intented to mark also functions as constexpr? - cgpzs - 30-10-2023

Thank you for the clarification!


RE: A7-1-2: Is it really intented to mark also functions as constexpr? - misra cpp - 30-10-2023

Thread closed