]> git.ipfire.org Git - thirdparty/gcc.git/commit
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)
commitb0db0df2b2f8e152aca2c8d19643e259dab23cbb
treee1ea255e4c54245f3358190a11e73e770f7c0d21
parent9a8c08aaad5e19f8f5dd5986a62c3a1148f61f3a
c++: -Wunused-value on ternary indexed by non-constant

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]