Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: gcc implicitly converts signed char to unsigned char and vice versa?

Tags:

c

types

gcc

I'm trying to learn C at got stuck with datatype-sizes at the moment.

Have a look at this code snippet:

#include <stdio.h>
#include <limits.h>

int main() {
    char a = 255;
    char b = -128;
    a = -128;
    b = 255;
    printf("size: %lu\n", sizeof(char));
    printf("min: %d\n", CHAR_MIN);
    printf("max: %d\n", CHAR_MAX);
}

The printf-output is:

size: 1
min: -128
max: 127

How is that possible? The size of char is 1 Byte and the default char seems to be signed (-128...127). So how can I assign a value > 127 without getting an overflow warning (which I get when I try to assign -128 or 256)? Is gcc automatically converting to unsigned char? And then, when I assign a negative value, does it convert back? Why does it do so? I mean, all this implicitness wouldn't make it easier to understand.

EDIT:

Okay, it's not converting anything:

char a = 255;
char b = 128;
printf("%d\n", a);    /* -1 */
printf("%d\n", b);    /* -128 */

So it starts counting from the bottom up. But why doesn't the compiler give me a warning? And why does it so, when I try to assign 256?

like image 936
j0ker Avatar asked Feb 03 '23 14:02

j0ker


1 Answers

See 6.3.1.3/3 in the C99 Standard

... the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

So, if you don't get a signal (if your program doesn't stop) read the documentation for your compiler to understand what it does.


gcc documents the behaviour ( in http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation ) as

  • The result of, or the signal raised by, converting an integer to a signed integer type when the value cannot be represented in an object of that type (C90 6.2.1.2, C99 6.3.1.3).

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.

like image 186
pmg Avatar answered May 13 '23 05:05

pmg