user4344762
user4344762

Reputation:

Is the return type of an expression always match the operands type?

In C++ the operands used in an expression must be of the same type (and if they are not, one operand is promoted to match the other).

My question is: can I assume that the return type of any expression will always match the type of its operands, or is there's an exception to this rule? For example is there's such a case:

typeY typeYVar = typeXVar / typeXVar2;

Even though both operands are of typeX, I am assuming that this expression will return a typeY value.

Note: I am talking about primitive types.


Edit: I am referring to the final type of operands, that is after a promotion (if any) is performed on them (whether the promotion is to make the type of operands the same, or because a char/short/etc. needs to be promoted to an int).

Upvotes: 0

Views: 134

Answers (3)

Rob
Rob

Reputation: 1974

Evaluation of an expression is largely independent of the type of variable the result is stored in.

If we do

int x = 4;
int y = 3;
long long z;
z = x/y;

The result of the expression "x/y" is of type int (and a value of 1). This value of 1 is then converted to be of type long long (yielding 1LL).

Neither x nor y are implicitly converted (or promoted) to be of type long long before doing the division. The result of the division is converted in order to do the assignment.

Some operations do involve implicit conversion (e.g. if dividing two variables of different types, there are specific rules about how promotion occurs)

Upvotes: 0

user743382
user743382

Reputation:

An obvious counter-example is pointer addition and subtraction:

const char *p = "Hello, world!";
const char *q = p + 1; // operands of type const char * and int, neither is converted to the other
auto diff = q - p; // two operands of type const char *, result has type ptrdiff_t

Relational operators are another obvious counter-example:

auto cmp = 1.23 < 4.56; // two operands of type double, result has type bool (or int in C)

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

Yes, this is definitely possible - for example, when you use expressions that require integral promotions:

char a = 'a', b = 'b';
int c = a + b; // Operator + promotes a and b to int
cout << typeid(a+b).name() << endl; // prints "i"

Demo.

Upvotes: 3

Related Questions