0

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?

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
shibuya
  • 3
  • 3

3 Answers3

3

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.

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • undefined behavior or implementation defined? I mean the difference described here: http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior – PiotrNycz Apr 27 '16 at 11:47
  • @user6261180 No problem. It is a little short but I wanted didn't want to explain what is happening for you since it may not happen to everyone. – NathanOliver Apr 27 '16 at 11:58
1

There is no operator+(unsigned char, unsigned char) in C++, it first promotes these unsigned char arguments to int and only then does the addition, so that the type of the expression is int.

And then that int whose value is too big to fit in unsigned char gets converted to unsigned char.

The standard says:

A prvalue of an integer type can be converted to a prvalue of another integer type. A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type. If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2**n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

For the second question, the answer is undetermined.

You can verify it yourself like this :

#include <iostream>

using namespace std;

int main()
{
    int a = 1;
    int b = 32767;
    int c = a+b;
    cout << c << endl;
}

The result will depend on your machine.