Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


In C the order of declaration and destruction doesn't matter as much, because C has no destructors. C++ would have similar issues, though.


I 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.


(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.


Only C89 requires this. Compilers have moved on.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: