GabrieleMartini
GabrieleMartini

Reputation: 1721

How to prevent unwanted variable assignment inside condition statement?

Missing equal sign inside assignment (typing = instead of ==) make unwanted assignment inside a condition statement. For example, consider the scenario below (this example is in C, but the question is valid also for interpreted code).

CASE A:

int g=1;

if ( g == 3 )
{
    printf("g is 3");   
}
else
{
    printf("g is not 3"); 
}

//this return: "g is not 3"

CASE B: (typo: missing = inside condition)

int g=1;

if ( g = 3 )
{
    printf("g is 3");   
}
else
{
    printf("g is not 3");
}

//this return: "g is 3" because of the assignment

Both the cases are formally correct, so the code will work but not as we want; and may be hard to debug.

How to prevent this situation? There is a solution that cover the interpreted code (for example javascript), apart static analyzers?

Upvotes: 0

Views: 315

Answers (1)

Govind Parmar
Govind Parmar

Reputation: 21562

The thing is, using an assignment inside a condition body for if, while, or for is perfectly valid C and is very often used intentionally. For example, I often find myself using the following skeleton code to create a window when writing a Win32 API GUI:

if((hWnd = CreateWindowExW(...)) == NULL)
{
    MessageBoxW(NULL, L"Window creation failed", L"Error", MB_OK | MB_ICONSTOP);
    return GetLastError();
}

If the test is solely for equality and you want to avoid using the = operator accidentally, one thing you can do is get into the habit of putting the r-value on the left side of the operator, so that if you accidentally use =, it will produce a compilation error:

char *p = malloc(100000);
if(NULL == p)
{
    // handle null pointer
}

Obviously, this only works if at least one side of the comparison is an r-value or a const variable.

Upvotes: 1

Related Questions