Programming/Structs: Difference between revisions
Brodriguez (talk | contribs) (Create page) |
Brodriguez (talk | contribs) m (Brodriguez moved page Structs to Programming/Structs) |
(No difference)
|
Latest revision as of 17:26, 25 October 2020
The term "struct" stands for "structure". Conceptually, it can be thought of as a grouping of variables.
Alternatively, a struct can be though of as a class that has no constructor or methods associated with it.
Note that some higher level languages, such as Java, don't have support for Structs. In these instances, you can accomplish the same thing with a class.
General Concept
Hypothetically, let's say a business has a custom program. This program has a few "core" variables that are used throughout.
We can call them Revenue
, Expenses
, and Profit
.
Let's also suppose that, in this program, any time one of the above variables is uses, the rest are guaranteed to be used shortly after.
Finally, let's assume that we are avoiding use of global variables, to avoid cluttering namespace.
One way to write this is to individually pass these three variables back and forth to all functions that need it:
my_function(int revenue, int expenses, int profit) { ... return revenue, expenses, profit }
However, depending on how large the program is and how many functions it has, this can get repetitive and easy to mess up.
Alternatively, it can be much cleaner to group these into a single object, aka a struct.
struct costs { int revenue, int expenses, int profit, }
Then any time you need to reference these values, instead pass the struct that contains them:
my_function(struct costs) { ... return costs; }
While this example is somewhat contrived, it shows how useful it can be to group variables together into a single object.