I read that in C++17 we can initialize variables in if
statements like this
if (int length = 2; length == 2) //execute something
Instead of
int length = 2; if (length == 2) //do something
Even though it is shorter, it affects the code readability (especially for people who don't know this new feature), which I suppose is a bad coding practice for large software development.
Is there any advantage of using this feature other than making the code shorter?
C++17 If statement with initializer C++17 has extended existing if statement's syntax. Now it is possible to provide initial condition within if statement itself. This new syntax is called "if statement with initializer". This enhancement simplifies common code patterns and helps users keep scopes tight.
Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.
Control blocks like If statements in Python do not count and the variables used or initialized inside the block of an If statement can also be used and accessed outside its scope.
Generally, all variables should be explicitly initialized in their declaration. The descriptive comment is optional. In most cases, variable names are descriptive enough to indicate the use of the variable. However, provide a comment if further description is appropriate or if an initial value is unusual.
It limits the scope of length
to the if
alone. So you get the same benefits we originally got when we were allowed to write
for(int i = 0; i < ... ; ++i) { // ... }
Instead of the variable leaking
int i; for(i = 0; i < ... ; ++i) { // ... }
Short lived variables are better for several reasons. But to name a couple:
The shorter something lives, the less things you need to keep in mind when reading unrelated lines of code. If i
doesn't exist outside the loop or if
statement, then we don't need to mind its value outside of them. Nor do we need to worry its value will interact with other parts of the program that are outside of its intended scope (which may happen if i
above is reused in another loop). It makes code easier to follow and reason about.
If the variable holds a resource, then that resource is now held for the shortest period possible. And this is without extraneous curly braces. It's also made clear the resource is related to the if
alone. Consider this as a motivating example
if(std::lock_guard _(mtx); guarded_thing.is_ready()) { }
If your colleagues aren't aware of the feature, teach them! Appeasing programmers who don't wish to learn is a poor excuse to avoid features.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With