c - Is a type cast necessary while converting between signed int and unsigned int? -


i tried assigning signed int unsigned int.

#include <stdio.h>  int main() {   int a;   unsigned int b;   scanf("%d", &a);   b = a;   printf("%d %u\n", a, b);   return 0; } 

i hoping compiling cause warning assigning int value unsigned int variable. did not warning.

$ gcc -std=c99 -wall -wextra -pedantic foo.c $ echo -1 | ./a.out -1 4294967295 

next tried assigning unsigned int signed int.

#include <stdio.h>  int main() {   int a;   unsigned int b;   scanf("%u", &b);   = b;   printf("%d %u\n", a, b);   return 0; } 

still no warning.

$ gcc -std=c99 -wall -wextra -pedantic bar.c $ echo 4294967295 | ./a.out -1 4294967295 

two questions:

  1. why no warnings generated in these cases though input gets modified during conversions?
  2. is type cast necessary in either of cases?

code 1: conversion well-defined. if int out of range of unsigned int, uint_max + 1 added bring in range.

since code correct , normal, there should no warning. try gcc switch -wconversion produce warning correct conversions, particularly signed-unsigned conversion.

code 2: conversion implementation-defined if input larger int_max. implementation on defines inverse of conversion in code 1.

typically, compilers don't warn implementation-defined code well-defined on implementation. again can use -wconversion.

a cast not necessary , general principle, casts should avoided can hide error messages.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

python 3.x - PyQt5 - Signal : pyqtSignal no method connect -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)