c - Fixpoint-Overflow-Traps for int16_t and int8_t -


i have complicated program fixed-point arithmetic.

it seems there occasional overflows.

to find them have set flag -ftrapv. seems work int32_t. correct?

is there way achieve same behavior int16_t , int8_t?

here test code:

#include <stdio.h> #include <stdint.h>  int main(void) {     int8_t int8 = 127;     int8 += 1;     printf("int8: %d\n",int8);      int16_t int16 = 32767;     int16 += 1;     printf("int16: %d\n",int16);      int32_t int32 = 2147483647;     int32 += 1;     printf("int32: %d\n",int32); } 

i compile with:

rm a.out; gcc -ftrapv main.c && ./a.out 

and get:

int8: -128 int16: -32768 aborted 

my compiler version gcc (ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609.

note: of answers refer test program have incorrectly written before.

i have no idea trying do.

  • the maximum value int8_t can hold 127 , not 255.
  • the maximum value int16_t 32767 , not 65535.
  • the maximum value int32_t can hold indeed 2147483647.

so code does:

  • int8_t int8 = 255; assign value 255 variable can hold maximum of 127. won't fit, invoke implicit conversion in implementation-defined manner. end value -1. implicit lvalue conversion , no signed integer overflow.

  • printf("int8: %d\n",int8 + 1); print result of -1 + 1. 0. no overflow anywhere.

  • the same thing happens 16 bit variable, implicit conversion, end value -1, print 0.

  • int32_t int32 = 2147483647; line different other two, set int32 maximum value can contain. if take +1 on that, signed integer overflow invokes undefined behavior.

on top of that, 2 smaller integer types can't overflow upon addition, if code doing (which doesn't). both operands integer promoted type int - there no overflow. see implicit type promotion rules detailed explanation how works.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -