Why constexpr is working with cin and non const | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why constexpr is working with cin and non const

Why constexpr is working with cin and non const? one variable is not marked as const int and other is dependent on user input. Should not it be a compile time error? https://code.sololearn.com/cN6KvydzhSwK/?ref=app

1st Dec 2022, 5:32 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 2
The constexpr keyword is only a guideline for the compiler, to evaluate the result during program compilation, rather than at runtime, WHEN POSSIBLE. Even if you don't use cin, the variables a and b in your program are still evaluated at runtime, because they are not declared as constant. Using constexpr in this situation seems useless to me. https://www.learncpp.com/cpp-tutorial/constexpr-and-consteval-functions/ "To be eligible for compile-time evaluation, a function must have a constexpr return type and not call any non-constexpr functions. Additionally, a call to the function must have constexpr arguments (e.g. constexpr variables or literals)."
2nd Dec 2022, 6:02 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Thanks... i got it now... its a request and compiler will decide.. If it cant be evaluated as constexpr, it will not throw error
2nd Dec 2022, 7:49 AM
Ketan Lalcheta
Ketan Lalcheta - avatar