Search code examples
c++return-valueunsigned-char

Value of a+b and char type


I am working in C++ and I had (as an exercise) to write on paper 2 answers. The first question: if we have the following declarations and initialisations of variables:

unsigned char x=250, z=x+7, a='8';

What is the value of the expression?

z|(a-'0') // (here | is bitwise disjunction)

We have unsigned char, so the number z=x+7 is reduced mod 256, thus, after writing the numbers in binary, the answer is 9.


The next question: a and b are int variables, a=1 and b=32767.

The range of int is [-32768, 32767]. We don't have an unsigned type here. My question is: what is the value of a+b? How does this work with signed data types if the value of a certain variable is greater than the range of that data type?


Solution

  • The next question: a and b are int variables, a=1 and b=32767.

    [...]My question is: what is the value of a+b?

    Its undefined behavior. We cant tell you what it will be. We could make a reasonable guess but as far as C++ is concerned signed integer overflow is undefined behavior.