Search code examples
ctype-conversionundefined-behaviorimplicit-conversioninteger-promotion

Question on Usual Arithmetic Conversions - GCC Compiler


I'm trying to understand implicit datatype conversions in C. I thought that I had understood this topic, but yet the following code example is still confusing me.

Specifically, I have read about Usual Arithmetic Conversions and Integer Promotion previously from drafts of the C Standard.

    unsigned short int a = 0;
    printf("\n%lld", (signed int)a - 1);

I am compiling using GCC.

unsigned short int is 2 bytes. int is 4 bytes.

When I run this code, I get the following result: 4294967295

I expected the result -1.

This is what I expected to happen:

  1. Typecast takes precedence, and LHS of - becomes signed int.

  2. - operation is carried out. No integer promotion or implicit conversions occur here, as LHS and RHS are already both signed int. The result of the operation is -1 with datatype signed int.

  3. Within printf statement, value -1 is retained within the conversion to long long int, and -1 is displayed as the result.

Can someone please explain where the flaw in my logic is?


Solution

  • It's undefined behaviour due to %lld being the inappropriate format specifier for an int type.

    Yes indeed (signed int)a - 1 is an int type with value -1, but the printf call is the undefined part. There's nothing in the C standard to suggest that a conversion to long long occurs.