gcc optimization? bug? and its practial implication to project

前端 未结 5 1413
谎友^
谎友^ 2021-01-11 16:11

My questions are divided into three parts

Question 1
Consider the below code,

#include 
using namespace std;

i         


        
5条回答
  •  时光说笑
    2021-01-11 16:29

    OK, so this was almost six years ago and the question is answered. Still I feel that there are some bits that have not been adressed to my satisfaction, so I add a few comments, hopefully for the good of future readers of this discussion. (Such as myself when I got a search hit for it.)

    1. The OP specified using gcc 4.1.2 without any special flags. I assume the absence of the -O flag is equivalent to -O0. With no optimization requested, why did gcc optimize away code in the reported way? That does seem to me like a compiler bug. I also assume this has been fixed in later versions (for example, one answer mentions gcc 4.5 and the -fno-strict-overflow optimization flag). The current gcc man page states that -fstrict-overflow is included with -O2 or more.

    2. In current versions of gcc, there is an option -fwrapv that enables you to use the sort of code that caused trouble for the OP. Provided of course that you make sure you know the bit sizes of your integer types. From gcc man page:

    -fstrict-overflow 
    .....
    See also the -fwrapv option. Using -fwrapv means that integer signed overflow 
    is fully defined: it wraps. ... With -fwrapv certain types of overflow are 
    permitted. For example, if the compiler gets an overflow when doing arithmetic 
    on constants, the overflowed value can still be used with -fwrapv, but not otherwise. 
    

提交回复
热议问题