3 ms·
For C users. And C++ users: In C++ we can declare variable in the while or if statement: https://en.cppreference.com/w/cpp/language/while https://en.cpprefere
by ho_schi 2y ago
For C users. And C++ users:
In C++ we can declare variable in the while or if statement:
https://en.cppreference.com/w/cpp/language/while https://en.cppreference.com/w/cpp/language/while
https://en.cppreference.com/w/cpp/language/if https://en.cppreference.com/w/cpp/language/if
It's value is the value of the decision. This is not possible with C [1].
Since C++17 the if condition can contain an initializer:
Ctrl+F if statements with initializer
https://en.cppreference.com/w/cpp/language/if https://en.cppreference.com/w/cpp/language/if
Which sounds like the same? Now you can declare a variable and it value is not directly evaluated, you also can compare it in a condition. I think both are neat features of C++, without adding complexity.
[1] Also not possible with Java.
- trelane 2y agoDeclaring a variable in a loop or if statement is supported since C99: https://en.wikipedia.org/wiki/C99 https://en.wikipedia.org/wiki/C99 Also in Java: https://www.geeksforgeeks.org/for-loop-java-important-points/ https://www.geeksforgeeks.org/for-loop-java-important-points...
- maccard 2y agoNo, declaring a variable in a `for` loop is supported in C99 but you can't do if-init.
- trelane 2y agoAh, you're right (finally tried it out). But it 100% works in a loop (usually for loop)
- maccard 2y agoIt’s one of those things that I never knew I wanted until I started using it, and now i miss it when it’s not available.The reason you want it is the same reason you want to declare a variable in the statement of a for loop rather than pre declaring and using a while loop
- trelane 2y agoI've used it in go a lot. If you want to kludge it, you can still put a block around the if. But it's not nearly as nice
- deleted 2y ago[deleted]
- ho_schi 2y agoYou do :) My post was about while and if and you repeatingly bring up for. The for statement is another statement.
- ho_schi 2y agoRegarding Java: It is possible that you confuse while- and for statements?