using static variables as fake globals in C

global variables can be a life safer solution in cases of having abstract complex structs that we need to access from many part of the our code and free maybe, but sadly they’re a bad practice and can raises issues when the complexity of our programs reaches a hard to control degree (or forbidden by your school assignments rules like my case), so what’s the solution?

it’s commune knowledge that static variables maintain their values even when they’re out of their scope but when we start writing more complex code in C a need for applying that concept to our allocated structs variables raises more and more which can be easily done in the following way:

let’s assume we have a struct that represents a point in space with coordinates x and y:

the trick to preserve the value of this struct pointer variable through all our code is in the way of writing our object/struct constructor that we make our struct pointer static in it:

now we can access the same struct variable that our constructor returns whenever we call our constructor no matter where in our code, but we can’t change it non manually via the constructor so we code a setter:

and to show you a fully working example of how this can be used:

the output is:

p->x: 4 p->y: 8
p->x: 42 p->y: 1337

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Reverse Proxy In a Nutshell

Top 7 Multilingual Plugins For WordPress — Complete Reviews

multilingual wordpress plugin reviews

LeetCode — Sqrt(x)

Game Genie Cheat Files In Emulator

Leetcode 104 — Maximum Depth of Binary Tree

Connecting to MS SQL on compute in GCP using Cloud IAP.

Bring New Idea on App Development Process

Event Bus in php using AMQP Library and RabbitMQ

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Khalil Hafni

Khalil Hafni

More from Medium

Friendly Introduction Pointers in C++

C++20 Concepts: Part 5 (Advanced use cases)

How I learned Yocto Project and Qt and why you would do the same

Looping: do-while loop In C