C language: implicit type conversion examples

One of the most hardcore stuff in C lang is implicit type conversion. If you don’t watch for it – you will be in biiig trouble. Take a look at this code:

#include <stdio.h>

int main (void)
{

//by default 'int' is signed
int foo = -100;

printf ("int foo = %d; unsigned int foo = %u\n", foo, foo);

// lets take unsigned int
unsigned int bar = 10U;

// when we have addition of singned and unsigned variables,
// C transfer signed to unsigned by default
long long int qux = foo + bar;

// so -100 + 10 will become:
printf ("bar + foo = %lld\n", qux);

/* Another case: */

char fred = 'Я';  // char is !signed! integer by default
printf ("<Я> char as an integer = %d\n", fred);

int baz = (int)fred * 2;

printf("<Я> * 2 = %d\n", baz);

getchar();
}

 

Posted in C lang | Leave a comment