[cfe-dev] Compile-time ternary operator

Anton Bachin antonbachin at yahoo.com
Fri Jan 18 13:26:19 PST 2013


You're right, it's a warning - but I almost always compile with -Werror. I suppose I could disable this one diagnostic. I currently have another workaround in place.

I don't think this is a reasonable thing to warn about, however. I imagine the warning was originally inserted because of an assumption that the expressions in the true-case and false-case are, in a way, independent of the expression in the condition (before the `?`) - but there is a lot of useful code for which that won't be so.

test.cc:2:41: error: array index -1 is before the beginning of the array
      [-Werror,-Warray-bounds]
constexpr int value = true ? array[0] : array[-1];
                                        ^     ~~
test.cc:1:1: note: array 'array' declared here
constexpr int array[] = {1};
^
1 error generated.

On Jan 18, 2013, at 4:16 PM, David Blaikie <dblaikie at gmail.com> wrote:

> On Fri, Jan 18, 2013 at 8:29 AM, Anton Bachin <antonbachin at yahoo.com> wrote:
>> Hello,
>> 
>> I am making use of the ternary operator (?:) in a compile-time computation. An illustrative example:
>> 
>> constexpr int array[] = {1};
>> constexpr int value = true ? array[0] : array[-1];
>> 
>> int main()
>> {
>>    return 0;
>> }
>> 
>> In the actual program, the condition determines whether it is safe to perform the access in the false-case.
>> 
>> Clang fails to compile this program, complaining about the out-of-bounds access in the false-case. This is the case with clang++ 3.1 on BSD and OS X.
> 
> Could you show the exact clang output?
> 
>> GCC 4.7 compiles the program just fine.
>> 
>> Is this a bug or the intent? If it's a bug, has it been fixed in 3.2?
> 
> ToT Clang still warns about the out of bounds access (which could be
> considered reasonable, or not - since it is unreachable - perhaps that
> should be under our "analysis based warnings" that don't fire unless
> the code is reachable) but it doesn't fail to compile.





More information about the cfe-dev mailing list