Program execution

Why the program below prints -128

#include <stdio.h>
main()
{
    char i = 0;
    for (; i >= 0; i++)
        ;
    printf("%d",i);
}

You can also assign an int char value without casting it. And if I used the print statement in a for loop, it prints to 127, which is true, but the current version of this program prints -128. Why

+4
source share
2 answers

If charthis is a type signedon your platform, then the behavior of the program is undefined : type overflow signedis undefined behavior in C.

2- 8- -128 -, 8- +128. , , . -128 - , , . ( " " ). .

+5

N1570, char, : (Emphasis mine)

6.2.5

15 char, char unsigned char . char, , , char, char.

, :

9 . , , , , .

, UCHAR_MAX == 127 ( 255,), 127 + 1 = (127 + 1) % (UCHAR_MAX + 1) = (127 + 1) % (127 + 1) = 0.

, undefined, , . CHAR_MAX + 1 CHAR_MIN, 0 . , " undefined" , , .

, char , CHAR_MAX + 1 == CHAR_MIN. ? , , , . .

+2

Source: https://habr.com/ru/post/1628992/


All Articles