Since very little is ever removed from C++, all the inconsistencies in C++ are still there.
int val;
bool valueSet = getFoo(&val);
if (valueSet) {}
printf(“%d”, val); // oops
The bug can be avoided entirely with C++ if (int val; getFoo(&val)) // if you control getFoo this could be a reference which makes the null check in getFoo a compile time check
{}
printf(“%d”, val); // this doesn’t compile.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/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
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.
Also in Java: https://www.geeksforgeeks.org/for-loop-java-important-points...
{ int val; if (getFoo(&val)) {
...
}}
Both ways of expressing this are weird, but stating that this can't be achieved with C is dishonest in my opinion. {
int val;
if (getFoo(&val)) {
}
printf("%d", val);
}
The bug is still possible, as you've introduced an extra scope that doesn't exist in the C++ version.Also, this was one example. There are plenty of other examples.
But i agree the C++ if(init;cond) thing was new to me.
If you rewrote it in a more modern way and changed the API
std::optional<int> getFoo();
if (auto val = getFoo()) {}
There are lots of improvements over C’s type system - std.array, span, view, hell even a _string_ classThe problem is all the folks that insist coding in C++ as if it was C, ignored all those C++ improvements over C.