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

Also... Arrays have block scope. So if you have a function that declares an array, operates on it, then returns a pointer to that array, it's undefined behaviour.

This was very confusing to me when I learned C because it's one of those undefined behaviours that appears to work properly in trivial programs (at least with the compiler I was using).




If you have a function that declares anything and returns a pointer to it, it's undefined behavior. Because variables have block scope.


EDIT: ugh, this is not working right. I can't figure out how to get the asterisks to not italicize ( I was trying to show an example).

Variables have block scope, but storage duration need not. If you return a pointer to a block of memory allocated within a function, that is not undefined behaviour. If you return a pointer an array declared within the function that is (if you return a pointer to a static array declared within a function that is not). That's the contrast I was trying to point out.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

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

Search: