8 ms·
Fyi Rust has solved this problem; the compiler forbids the use of undefined variables. Compile error example: let x; println!("x:{}", x);
by markus2012 11y ago
Fyi Rust has solved this problem; the compiler forbids the use of undefined variables. Compile error example:
let x;
println!("x:{}", x);
- xamuel 11y agoNot a rust programmer so forgive me if this is a dumb question. Sometimes in C one might initialize a variable by passing a pointer to it to an init function: void f( void ) { int i; bool success; success = init( &i ); if ( success ) do_stuff( i ); } That "init" function might be located in a separate .c file, so there's no way for the compiler to know whether or not the memory whose address is passed to init is initialized or not. So how can Rust "solve" the problem? Does Rust simply not allow taking addresses of variables? Or does it not use .o files, compile all codefiles at once and actually analyze globally for uninitialized variables?
- jamii 11y agoYou can't construct a pointer to a potentially uninitialised variable - http://is.gd/xkrJ3l http://is.gd/xkrJ3l The idiomatic way to do this would be: match init() { Some(i) => do_stuff(i), None => panic!("Oh noes"), }
- AaronFriel 11y agoThe `init` function you use would not be valid. You would instead write something like this: fn f() { if let Some(i) = init() { do_stuff(i); } } In this case, the `init` function would return an `Option<i32>`. In a failure state, this would return `None`, and the pattern match would fail. In a success state, this would return `Some(i)`, where i corresponds to the variable you describe. The Rust pattern is not only safer, but briefer than yours. It describes the code flow such that you can't remove or repeat a part and end up with inadvertently broken code, and it's memory safe. There is no way for `init` to blow up the stack (whereas in your example, a malicious or buggy init can use the address of i to smash the stack.)
- arielby 11y agoRust doesn't allow this direct use-case. You can have conditionally-successful initialization by returning an `Option` or `Result`, however.
- anon4 11y agoThis should be an error and you should be required to write int i = 0; // or some other default value
- SamReidHughes 11y agoAnd dozens of other languages.