Saturday, February 19, 2022

[SOLVED] Is there an option to make GCC warn me if I use "=+" instead of "+=" operator?

Issue

For an example:

#include <stdio.h>
#define TS_SIZE 188

int main(void)
{
    volatile int offset = 0;
    volatile int len = 10;

    for (int i=0; i < len; i++)
    {
        offset =+ TS_SIZE; /* This should be += */
    }
    
    printf("Offset: %d \n", offset);
    return 0;
}

Tried "-Wall, -Wextra and, -pedantic", not luck even with latest GCC (10.x) on godbolt compiler explorer.

Note: This is just a small contrived example code. Volatile's used for obvious reasons.


Solution

It's not really the compiler's job. A compiler is there to check if your code is valid C and then translate your source code into machine code for the target system.

However, compilers have become increasingly friendly over the years and sometimes warn against common bugs, poorly-defined behavior or other potential run-time misbehavior. This friendliness shouldn't be mistaken for some guarantee that the compiler will catch all such bugs though.

While compilers tend to warn for if(a = b), gcc with max warnings doesn't even warn for something obvious such as int arr[2]; arr[2]=1; (clang and icc does). And as you noticed, not for =+, =! etc either.

The solution for this is to have a software quality system that covers as many known issues as possible. Not just relying on compiler warnings alone, but taking the step to become a professional software engineer. That means coding style guides, coding standards for using a safe subset of C, static analysis tools, code "beautifiers" and peer code reviews.

Static analysers can find a lot of bugs that the compiler doesn't look for, but perhaps not this particular bug unless you explicitly configure it to look for it. A coding standard + code beautifier ought to transform the code into offset = +TS_SIZE; though, after which manual code review will easily spot the bug.


EDIT: as pointed out in comments, =+ was once valid C in very early pre-K&R versions. Some history lessons here: What does =+ mean in C?, see the great answer by Jonathan Leffler in particular.



Answered By - Lundin
Answer Checked By - Clifford M. (WPSolving Volunteer)