Modern programming languages (such as C++17, Go, etc.) provide a very handy feature, if statement with initializer(s). They let you declare and initialize variables that, if present, are only visible within the if block and the associated else block.
In the code snippets below, the val
variable is within the scope of if-else blocks.
if (bool val = is_even(101); val) {
std::cout << val;
} else {
std::cout << val;
}
if val := is_even(101); val {
fmt.Println(val)
} else {
fmt.Println(val)
}
However, this feature is nothing more than syntactic sugar, and you can easily mock this feature in other programming languages. Hacks to do so are listed below:
Consider the following example:
#include <stdio.h> #include <stdbool.h> bool is_even(int n) { return (n & 1) == 0; } int main(void) { int n = 4; bool val = is_even(n); if (val) { // 1 ==> TRUE printf("%i\n", val); } else { // 0 ==> FALSE printf("%i\n", val); } //val is also accessible below val = false; return 0; }
The val
variable gets leaked/exposed to the code below the if-else statements, which could create problems in some cases. A common way to get around this problem is to encapsulate the variable(s), along with the if-else block, within a block. This is shown below:
#include <stdio.h> #include <stdbool.h> bool is_even(int n) { return (n & 1) == 0; } int main(void) { int n = 4; { //If with initializer(s) block bool val = is_even(n); if (val) { printf("%i\n", val); } else { printf("%i", val); } } //End block //val is not accessible now val = false; return 0; }
The above code will now result in a compilation error:
main.c: In function ‘main’:
main.c:24:2: error: ‘val’ undeclared (first use in this function)
val = false;
^~~
So, in this way, you can mock the if statement with initializer(s) in the C programming language.
You can also apply the same hack in other programming languages (like C++11, C++14, Java, JavaScript, etc.) by nesting the variables and if-else statements in a block.
RELATED TAGS
CONTRIBUTOR
View all Courses