4 ms·
> Some people when they see my code, have the urge to modify it so that x is initialized to 0 before the branches. But this hides bugs. Something like Java's f
by gopalv 8y ago
> Some people when they see my code, have the urge to modify it so that x is initialized to 0 before the branches. But this hides bugs.
Something like Java's final would be useful in such a scenario.
I write code which looks exactly like this, except I only do this for final variables - the compiler throws an error if I add a branch which doesn't explicitly set it.
- maxxxxx 8y ago" the compiler throws an error if I add a branch which doesn't explicitly set it." That's pretty useful.
- twic 8y agoIt is! It's called definite assignment: https://docs.oracle.com/javase/specs/jls/se10/html/jls-16.html https://docs.oracle.com/javase/specs/jls/se10/html/jls-16.ht... Java was my first language, so i took it for granted; i was alarmed when i found out that C and C++ don't have it. It's saved my bacon too many times to count. FWIW, Rust does have this rule; this code: fn show(x: usize) { let message; if x % 2 == 0 { message = "even"; } println!("{} is {}", x, message); } is rejected with error E0381: https://doc.rust-lang.org/stable/error-index.html#E0381 https://doc.rust-lang.org/stable/error-index.html#E0381
- maxxxxx 8y agoI am not up to date with latest C++ developments but I wonder if there is something you could build with template magic that would provide this in C++.
- jcranmer 8y agoThis is hard to do in C/C++: int val; if (do_something(&val)) { ... } Is val initialized or not? Note that passing in addresses of values is the standard way of getting around the fact that C/C++ does not support multiple return values.