lundi 5 février 2018

Runtime errors with constexpr

Consider the below code snippets

constexpr int div( int x, int y)
{
    return (x/y);
}

constexpr int div_by_zero( int x)
{
    return (x/0);
}

Case 1 :

int x = div(10,0);

This compiles successfully (with both gcc and clang) but produces the below runtime error.

Floating point exception (core dumped)

Case 2 :

int y = div_by_zero(10);

This gives a Compiler error,

(g++ -std=c++17) division by zero is not a constant expression

NOTE : clang does not throw error even in this case

And also Compiler warnings:

(clang++ -std=c++17), division by zero is undefined [-Wdivision-by-zero]

(g++ -std=c++17), division by zero [-Wdiv-by-zero]

For Case 1, why the compiler does not complain even when the value for second argument is known(i.e. zero) during the compile time ?

Aucun commentaire:

Enregistrer un commentaire