3 ms·
val ceases to exist before the reference ceases to exist, beacuse it's declared after. So after val is destroyed, the reference is invalid. Declare val earlie
by SamReidHughes 12y ago
val ceases to exist before the reference ceases to exist, beacuse it's declared after. So after val is destroyed, the reference is invalid. Declare val earlier. Your code would be very nutty in C too.
- borrowwhatnow 12y agoI think I disagree with the "your code would be nutty in C" comment. Since C requires all variables to be declared at the top of the scope, and the order of declaration doesn't matter for purposes of allocation, there's no reason to worry about the ordering in this case.
- SamReidHughes 12y ago(C does not require all variables to be declared at the top of the scope.) Even if you're using a version of C that does, the order of variables implies something about their lifetimes and your code could make somebody refactoring more likely to believe they can lift the pointer out to the containing scope, or put the int in a smaller scope.
- amyjess 12y agoOnly C89 requires this. Compilers have moved on.
- mbrubeck 12y agoIn C the order of declaration and destruction doesn't matter as much, because C has no destructors. C++ would have similar issues, though.