lefticus / cpp_weekly

The official C++ Weekly Repository. Code samples and notes of future / past episodes will land here at various times. PR's will be accepted in some cases.
The Unlicense
709 stars 26 forks source link

Curing beginner's mistakes #254

Open hskoglund opened 1 year ago

hskoglund commented 1 year ago

Channel

"C++Weekly"

Topics Recently I've been helping a student, he's writing this kind of code: // a simple main.cpp:

include

int main() { bool b1 = false; bool b2 = "false"; std::cout << "b1 = " << b1 << ", b2 = " << b2 << "\n";

int i1 = 2 - 1;
int i2 = "2" - "1";
std::cout << "i1 = " << i1 << ", i2 = "<< i2 << "\n";

return 0;

} //

This is perfectly valid C++ code but the student expects b1 and b2 to be the same, as well as i1 and i2. I remember when I started with C I sometimes wrote char* c = "Hello" + "there"; and c would be the sum of the two pointers :-( Thankfully in C++ this addition is illegal.

Do you know of any tool/analyzer that can detect these rookie mistakes? Rgrds Henry Length

5 minutes main.txt

fcolecumberri commented 1 year ago

Jason has even already made a video about it. bool b2 = "false" is only valid because it is valid to implicit convert char* to bool (same with int). Just remove implicit conversions.

https://www.youtube.com/watch?v=T97QJ0KBaBU

hskoglund commented 1 year ago

Aha, thanks for the pointer! I like the text at the start of that video "This feature MUST GO" 👍Couldn't agree more.