Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to compile a simple C++17 program

Tags:

c++

c++17

I am trying to use C++17 if constexpr feature but fail to compile a simple function.

Code:

template <auto B>
int foo()
{
    if constexpr(B)
    {
        return 1;
    }
    else
    {
        return 2;
    }
}  // <- I get an error here 

int main()
{
    return foo<false>();
}

The error output by compiler:

<source>(12): error #1011: missing return statement at end of non-void function "foo<B>() [with B=false]"

  }

Used -std=c++17 -O3 -Wall -Werror compiler flags and icc 19.0.1 compiler.

Is this valid C++17 code? What is the reason behind this error?

like image 972
Empty Space Avatar asked Nov 03 '19 11:11

Empty Space


People also ask

Can you use g ++ to compile C?

gcc is used to compile C program. g++ can compile any . c or . cpp files but they will be treated as C++ files only.

Can you compile a .C file with a .cpp compiler?

If the C++ compiler provides its own versions of the C headers, the versions of those headers used by the C compiler must be compatible. Oracle Developer Studio C and C++ compilers use compatible headers, and use the same C runtime library. They are fully compatible.

Can C code can be complied in CPP compiler?

Due to this, development tools for the two languages (such as IDEs and compilers) are often integrated into a single product, with the programmer able to specify C or C++ as their source language. However, C is not a subset of C++, and nontrivial C programs will not compile as C++ code without modification.


1 Answers

Is this valid C++17 code?

Yes, it's valid. Exactly one return statement will be discarded, while the other will remain. Even if none remain, C++ still allows you to omit a return statement from a function. You get undefined behavior if the function's closing curly brace is reached, but that's a risk only if execution reaches that point.

In your case, execution cannot reach such a point, so UB is not possible.

What is the reason behind this error?

You used -Werror, thus turning the compiler's false positive warning into a hard error. One workaround is to disable this warning around that particular function. This is purely a quality of implementation problem.

like image 56
StoryTeller - Unslander Monica Avatar answered Oct 27 '22 00:10

StoryTeller - Unslander Monica