Yoda Notation: A Coding Style for Safety

Yoda Notation: A Coding Style for Safety

In this article we will talk about a serious error of misassignment in programming, the one of the main reason for introduction of bugs. Later, we discuss how to find this issue with yoda notation and get it fixed.

Have you ever gone through a problem of mistakenly use of assignment operator = instead of equality operator == in conditional statements or comparisons. I am pretty sure you are. This is common error which can lead to unintended behavior in the program, as the intended logic is not executed as expected. In this article, we will explore this error, its consequences and at last its fixes.

Understanding the Misassignment Problem

Consider the following example where a function checks if a given number is divisible by 2:

#include <iostream>

bool isEven(int number) {
    if (number = 0) { // Misassignment here!
        return true;
    } else {
        return false;
    }
}

int main() {
    int input;

    std::cout << "Enter a number: ";
    std::cin >> input;

    if (isEven(input)) {
        std::cout << "The number is even." << std::endl;
    } else {
        std::cout << "The number is odd." << std::endl;
    }

    return 0;
}

In the isEven function, there is misassignment problem in the conditional statement if (number = 0). Instead of comparing number with 0, the assignment operator = is used, which assigns 0 to number and then evaluates to false. As a result, the function incorrectly identifies all numbers 

The Admin

The Admin

And yet you incessantly stand on their slates, when the White Rabbit: it was YOUR table,' said.