|
|
|
|
|
by maccard
464 days ago
|
|
Every language has inconsistencies, and C is not stranger to that. Much of c++’s baggage is due to C and you carry the same weight. That’s not to say that initialization isn’t broken in C++, but just like many features in many languages (off the top of my head in C - strcpy, sprintf, ctime are like hand grenades with the pin pre pulled for you) don’t use them. There’s a subset of C++17 that to me solves so many issues with C and C++ that it just makes sense to use. An example from a codebase I spend a lot of time in is 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.