hiddensunset4
hiddensunset4

Reputation: 6029

Unsure of -Wconversion behaviour

Given the following situation:

        char const a = (i == 0) ? 0 : copy[i - 1][j];

and

        char const a = (i == 0) ? '\0' : copy[i - 1][j];

Why does the first example produce the following: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion], and yet the second does not.

FWIW, copy is a char**.

This behaviour is not limited to char, the same can be seen for other integer sizes, so it appears it is a matter of promotion.

Upvotes: 2

Views: 160

Answers (2)

Lance Richardson
Lance Richardson

Reputation: 4610

The difference is that the type of '\0' is char, while the type of 0 is int.

The type of the result of the ternary operator when the second and third expressions have different arithmetic types is obtained by promotion to a common arithmetic type using the same rules that are used for types in arithmetic expressions. When one of the expressions has type "int" and the other has type "char", the type of the result is "int". The compiler is complaining that an "int" value is being assigned to a char variable.

A smarter compiler might keep track of the possible range of values for the result (which in this case is the same as the range of possible values for a "char"), and deduce that there is actually no possibility that the conversion from "int" to "char" will produce a change in value.

Upvotes: 1

Rob Kennedy
Rob Kennedy

Reputation: 163317

When one result argument to ?: is 0 (an int), the other result argument gets promoted to the same type — C++ requires that both possible results have the same type. Once the promotion is processed, the compiler discards the information about the original type, so at the time the warning is issued, the compiler no longer knows that what it's warning about had been a char all along. It doesn't complain about the second argument being demoted to char because it knows the literal 0 is a valid char value.

Upvotes: 3

Related Questions