Why should I always enable compiler warnings?

后端 未结 20 1638
时光说笑
时光说笑 2020-11-22 00:28

I often hear that when compiling C and C++ programs I should \"always enable compiler warnings\". Why is this necessary? How do I do that?

Sometimes I also hear tha

20条回答
  •  无人及你
    2020-11-22 01:08

    Non-fixed warnings will, sooner or later, lead to errors in your code.


    Debugging a segmentation fault, for instance, requires the programmer to trace the root (cause) of the fault, which usually is located in a prior place in your code than the line that eventually caused the segmentation fault.

    It's very typical that the cause is a line for which the compiler had issued a warning that you ignored, and the line that caused the segmentation fault the line that eventually threw the error.

    Fixing the warning leads to fixing the problem.. A classic!

    A demonstration of the above.. Consider the following code:

    #include 
    
    int main(void) {
      char* str = "Hello world!";
      int idx;
    
      // Colossal amount of code here, irrelevant to 'idx'
    
      printf("%c\n", str[idx]);
    
      return 0;
    }
    

    which when compiled with "Wextra" flag passed to GCC, gives:

    main.c: In function 'main':
    main.c:9:21: warning: 'idx' is used uninitialized in this function [-Wuninitialized]
        9 |   printf("%c\n", str[idx]);
          |                     ^
    

    which I could ignore and execute the code anyway.. And then I would witness a "grand" segmentation fault, as my IP epicurus professor used to say:

    Segmentation fault

    In order to debug this in a real world scenario, one would start from the line that causes the segmentation fault and attempt to trace what is the root of the cause.. They would have to search for what has happened to i and str inside that colossal amount of code over there...

    Until, one day, they found theirselves in the situation where they discover that idx is used uninitialized, thus it has a garbage value, which results in indexing the string (way) beyond out of its bounds, which leads to a segmentation fault.

    If only they hadn't ignored the warning, they would have found the bug immediately!

提交回复
热议问题