Select Page

Why should we always zero-out structs

by | September 15, 2015 | Development

I’m pretty sure that all professional C and C++ developers already know this, but it is not that common in Objective-C. Many OS X and iOS developers are not familiar with structs, or just forget how they work. Since many API’s in OS X and iOS are still in C, it is very important that every developer working with those API’s also knows how they work. One of the most used API’s is definitely Core Graphics, which we use in almost every iOS or OS X application.

Few days ago I was spending my time trying to figure out what was wrong in the code example below. It is something that is commonly used on iOS (for clarity this is a really simplified example):

So the code above sets the size and offsets the CGRect by 100.0 points in both x and y axes. The result should be a frame of: x = 100.0, y = 100.0, width = 1024.0, height = 768.0. This code worked fine during all development tests, so it was left untouched.

I thought that this is correct, as Objective-C value types are of zero value, if undefined, such as:

But once you build your app in Release configuration, this leads to undefined behaviour. This was causing a bug when I deployed the application over TestFlight.

This is an example of how easily Swift solves this problem, by forcing the developer to set all variables, before using the variable.

The correct code is below, making sure the struct is correctly set, before being used:

In the future, do not forget to initialize every struct. Or you will have to learn the hard way, like I did.

dal_face  DAL RUPNIK
  Founder of Unified Sense, tweeting at @thelegoless.