V
V
vvafree2016-08-02 13:04:41
Programming
vvafree, 2016-08-02 13:04:41

What happens if you pass a value greater than 255 to unsigned char C++?

Good afternoon. Now I'm studying reconciliation of images. I count on a piece of paper.
I got the value 355 when collapsing, how will it be stored in an unsigned char variable?
Will it be 255 or (355-255) = 100?
UPD
thanks everyone =)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
MiiNiPaa, 2016-08-02
@vvafree

I will be non-standard and say that the result may well be 355. Recently I worked with
C2000, and there char is 16-bit, in full accordance with the standard.
The full answer is that if you cram X into an unsigned char, the result will be X mod 2^n, where n is the bit depth of char.

F
Fat Lorrie, 2016-08-02
@Free_ze

Overflows are not automatically controlled. You can do it yourself, for example, using std::numeric_limits.
§5 draft of the C++ Standard :
1. [ Note: Clause 5 defines the syntax, order of evaluation, and meaning of expressions.60 An expression is a
sequence of operators and operands that specifies a computation. An expression can result in a value and
can cause side effects. — end note ]
....
4. If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values ​​for its type, the behavior is undefined .

A
Andrew, 2016-08-02
@OLS

99.
All arithmetic operations are performed at the hardware level in the ALU.
Modern general-purpose processors do not have additional hardware circuits for overflow checks - it (the check) can only be carried out independently (for example, by analyzing flags immediately after the operation). If there are no such checks, the bits of the register or memory cell of the result will simply contain the number that the bit grid can store, i.e. 8 least significant bits - 99.

V
Vladimir Martyanov, 2016-08-02
@vilgeforce

355 = 0x163, so unsigned char will be 0x63 or 99.
Checking the actual behavior in the debugger takes less time than writing a question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question