]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
c++: -Wunused-value on ternary indexed by non-constant
authorJohannes Altmanninger <aclopte@gmail.com>
Mon, 26 Jan 2026 10:16:53 +0000 (18:16 +0800)
committerJason Merrill <jason@redhat.com>
Wed, 28 Jan 2026 02:30:20 +0000 (10:30 +0800)
On this expression:

(true ? "a" : "b")[index()]

"g++ -Wunused-value" incorrectly produces

warning: left operand of comma operator has no effect [-Wunused-value]

From the -fdump-tree-original output:

if ((void) SAVE_EXPR <index ()>, 1)
  {
    (void) "a"[SAVE_EXPR <index ()>];
  }
else
  {
    (void) "b"[SAVE_EXPR <index ()>];
  }

Observe that we evaluate index() (and save it) before evaluating the
ternary expression.  Since "(void) SAVE_EXPR <index ()>" is ostensibly
side-effect free, we get this warning.  Since SAVE_EXPR is not useless,
this is a false positive. Also the comma operator compiler-generated,
so warning about it is wrong.

Suppress this warning for this implicit expression. Test that the
warning is gone for "$ternary[index()]" but we still warn on cases like
"$ternary[(1, 0)]".

gcc/cp/ChangeLog:

* typeck.cc (cp_build_array_ref): Suppress unused-value
warning for implicit comma expression.

gcc/testsuite/ChangeLog:

* g++.dg/warn/Wunused-value-2.C: New test.

Signed-off-by: Johannes Altmanninger <aclopte@gmail.com>
Co-authored-by: Jason Merrill <jason@redhat.com>
gcc/cp/typeck.cc
gcc/testsuite/g++.dg/warn/Wunused-value-2.C [new file with mode: 0644]

index 980f2d115a6649c3442aa37d652973bca1450ea9..40bb9828bcc6d8643cc09aa6a1f6697ddc0a4bb1 100644 (file)
@@ -4244,6 +4244,7 @@ cp_build_array_ref (location_t loc, tree array, tree idx,
            {
              idx = save_expr (idx);
              op0 = save_expr (op0);
+             warning_sentinel w (warn_unused_value);
              tree tem = build_compound_expr (loc, op0, idx);
              op0 = build_compound_expr (loc, tem, op0);
            }
diff --git a/gcc/testsuite/g++.dg/warn/Wunused-value-2.C b/gcc/testsuite/g++.dg/warn/Wunused-value-2.C
new file mode 100644 (file)
index 0000000..8125aa5
--- /dev/null
@@ -0,0 +1,18 @@
+// { dg-do compile }
+// { dg-options "-Wall" }
+
+static int index() { return 0; }
+
+volatile int global;
+static int index_with_side_effect() {
+    global += 1;
+    return 0;
+}
+
+int main(int argc, char **argv)
+{
+       const bool cond = argc == 10;
+       (void)(cond ? "" : "")[index()];
+       (void)(cond ? "" : "")[index_with_side_effect()];
+       (void)(cond ? "" : "")[(1, 0)]; // { dg-warning "left operand of comma operator has no effect" }
+}