Negation of characters in C

Is this behavior undefined? It outputs -128as a result:

#include<stdio.h>
int main()
{
    char i=-128;
    i=-i;
    printf("%d",i);
}

Explain, please.

+5
source share
6 answers

Two additions to -128 in the 8-bit value of -128.

Look at the binary values:

Original value: 10000000

Addition: 01111111

Increment: 10000000

+8
source

This is not undefined behavior. Assuming the type is charsigned on your platform, this is implementation-defined behavior. (C99, 6.3.1.3p3)

i = -i;

iat -ifirst advancing to int, therefore, -iis 128, and then 128converted to charwhole transformations.

, , 128 char :

(C99, 6.3.1.3p3) ; , , .

: , . gcc ( ):

N 2 ^ N, ;

http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html

, . (DSP) . ( char), i = -i; i 127.

+4

2

-128 = 0b10000000

, : - (- 128):

1 ():

~(-128) = 0b01111111

2 ( 1):

0b01111111 + 0b1 = 0b10000000 = -128

, 8- , - (- 128) = -128!

+1

char. 127. -128, +128, -128. .

0

undefined.

-1 , 1. , ,

~10000000+1 = 01111111+1 = 10000000

-128.

0

.

(Microsoft Visual Studio):

; File tmp.c
; Line 5
    push    ebp
    mov ebp, esp
    push    ecx
; Line 6
    mov BYTE PTR _i$[ebp], -128         ; ffffff80H
; Line 7
    movsx   eax, BYTE PTR _i$[ebp]
    neg eax
    mov BYTE PTR _i$[ebp], al
; Line 8
    movsx   ecx, BYTE PTR _i$[ebp]
    push    ecx
    push    OFFSET FLAT:$SG775
    call    _printf
    add esp, 8
; Line 9
    xor eax, eax
; Line 10
    mov esp, ebp
    pop ebp
    ret 0
_main   ENDP

.

And remember your double complement arithmetic.

Does it make sense?

====== ADD ======

It is really very simple. Here is a slightly modified example that may help clarify:

#include <stdio.h>

int
main (int argc, char *argv[])
{
  int i=-128, j, k, l;
  char c = i;
  printf("i: %d == 0x%x; c: %d == 0x%x\n", i, i, c,c);

  j=-i;
  k=~i;
  l=0-i;
  i=-i;
  c=-c;
  printf("%d, %d, %d, %d, %d\n",i,j,k,l,c);
  printf("0x%x, 0x%x, 0x%x, 0x%x, 0x%x\n",i,j,k,l,c);
  return 0;
}

Results:

i: -128 == 0xffffff80; c: -128 == 0xffffff80
128, 128, 127, 128, -128
0x80, 0x80, 0x7f, 0x80, 0xffffff80
0
source

All Articles