Why Does My Function Not Update My Variable?

So, as a result of some aberrant brain misfiring you’ve decided to start learning to code in C. You pretty quickly come across the idea of functions and your mind is blown.

Then you try to write a function and all is not well. Not well at all. In fact things are looking a bit peaky. You’re not getting the output you expect. Again. Gah. Why was it that you chose C again?

After a stupidly long time spent debugging you finally narrow down the problem to what is obviously nonsensical behaviour. C is clearly broken and you’ve just discovered a fatal flaw that has gone undetected in it for the past fifty years.

This classic and frequent problem encountered at some stage by pretty much all newbies (unless of course they cheated and read the manual) is pretty much universally heralded by “WTF is my function not updating my variable?”

C passes parameters by value – it makes local copy variables of parameters passed into functions. Passing in a pointer means you get a copy of the pointer but that copy is still pointing to the original memory. Pointers are a way to bypass C’s ‘pass by value’ mechanism. Sometimes I want changes I make to be reflected in the source of the data so I need to use reference semantics through pointers. Sometimes I want to manipulate data independently of the original data so I use copy or value semantics. The difference may appear subtle but it is important – a classic and frequent problem encountered by newbies is “Why does my function not update my variable?”

Leave a Reply

Your email address will not be published. Required fields are marked *