4 ms·
On the topic of intermediate variables, when I'm forced to use c89 I'm really shameless about introducing extra code blocks in the middle of other blocks. For e
by ufo 6y ago
On the topic of intermediate variables, when I'm forced to use c89 I'm really shameless about introducing extra code blocks in the middle of other blocks. For example,
{int i; for(i=0; i<N; i++){
/**/
}}
Still bothersome but better than having to declare everything at the top of the function, IMO.
- black3r 6y agoif I was forced to use c89 I would resign and find a better job...
- simias 6y agoI agree, but I think back then I didn't know this trick. I also abuse blocks in Rust, but it's more in order to placate the borrow checker...
- jfk13 6y agoThat's not necessarily abuse; it may be quite appropriate to explicitly limit something's lifetime.
- gnull 6y agoIndeed! I somewhat over-use this in Rust to initialize an immutable variable with mutating code. let var: Vec<u32>; // this one is immutable, will be initialized later { let mut var_; // mutable … // initialize var_ with some mutating code var = var_; // now move var_ to var, initializing the latter }
- steveklabnik 6y agoThis is a bit simpler as: let var = { let mut var = ... var }; that is, you can assign the result of the block directly. That way you don't need two variables with the _ name as the second.
- zerd 6y agoYou can also initialize it to an expression, e.g. let var = { let mut var_ = Vec::new(); var_.push(1u32); var_ };
- wizzwizz4 6y agoCouldn't you just write: let var: Vec<u32> = { let mut var_; … var_ }; Or, better still: let mut var: Vec<u32>; … let var = var;
- sixstringtheory 6y agoAs an example, in our C++ codebase at work we always place mutex locks inside their own scope blocks along with the critical sections of code they’re synchronizing. Helps readability and the scope determines when the mutex is released.
- rcoveson 6y agoI do something like this in "modern" Java to get for-each with index: { int i = -1; for (V v : list) { i++; // stuff } } While declaring i = -1 to start is a little gross, I like that it has some of the same properties as a normal for loop. No effect on parent scope, and all loop-logic is concentrated on the first (textual) line.