Bug 83273 - if constexpr does not fail with run-time conditions
Summary: if constexpr does not fail with run-time conditions
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 8.0
: P3 normal
Target Milestone: 8.0
Assignee: Jason Merrill
URL:
Keywords: accepts-invalid
Depends on:
Blocks:
 
Reported: 2017-12-04 17:07 UTC by Nicolai Josuttis
Modified: 2017-12-05 02:56 UTC (History)
5 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2017-12-04 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Nicolai Josuttis 2017-12-04 17:07:35 UTC
The following C++17 program should not compile, but it does:

#include <iostream>
int main()
{
  auto d = 42;
  if constexpr (d > 0) {
    std::cout << "oops \n";
  }
}

This even works inside a loop over different values of d.
And I found it trying this:
  if constexpr (auto obj = 42; obj == 0) {
    //...
  }
which should need a const/constexpr in the if initialization.

Reported as recommended by Jonathan Wakely.

Might also be a problem in 7.x
Comment 1 Jakub Jelinek 2017-12-04 17:37:31 UTC
tree
finish_if_stmt_cond (tree cond, tree if_stmt)
{
  cond = maybe_convert_cond (cond);
  if (IF_STMT_CONSTEXPR_P (if_stmt)
      && is_constant_expression (cond)
      && !value_dependent_expression_p (cond))
    {
      cond = instantiate_non_dependent_expr (cond);
      cond = cxx_constant_value (cond, NULL_TREE);
    }

So, if is_constant_expression is true, we do the right thing.
There is just no diagnostics if cond fails the is_constant_expression check and isn't value dependent.  We actually treat that if constexpr like normal if, with both then and else evaluated.
Comment 2 Jason Merrill 2017-12-04 22:52:39 UTC
Author: jason
Date: Mon Dec  4 22:52:07 2017
New Revision: 255390

URL: https://gcc.gnu.org/viewcvs?rev=255390&root=gcc&view=rev
Log:
	PR c++/83273 - constexpr if allows non-constant condition

	* semantics.c (finish_if_stmt_cond): Use require_constant_expression
	rather than is_constant_expression.
	* constexpr.c (potential_constant_expression_1) [LAMBDA_EXPR]: Allow
	in C++17.

Added:
    trunk/gcc/testsuite/g++.dg/cpp1z/constexpr-if13.C
Modified:
    trunk/gcc/cp/ChangeLog
    trunk/gcc/cp/constexpr.c
    trunk/gcc/cp/semantics.c
    trunk/gcc/testsuite/g++.dg/cpp1z/constexpr-if12.C
Comment 3 Jason Merrill 2017-12-04 23:06:13 UTC
Fixed.
Comment 4 Jason Merrill 2017-12-05 02:56:28 UTC
.