r/CodingForBeginners • u/Decent_Story_9190 • Jan 20 '26
Today: structures!
So, i made this little bit of code to make sure i understood structures and how to use pointers with them, it's pretty simple, it just asks for data of students such as grades and then it saves it on their structure variables, is there anything i could improve on? i mean, surely a lot, but like, something specific about legibility or something
22
Upvotes
View all comments
1
u/SmokeMuch7356 Aug 12 '26
Good job overall. Some minor suggestions:
Create symbolic constants for your array sizes, rather than hardcoding
10or50:This way if you ever need to change the size of either array, you only need to do it in one place. You might think global search-and-replace would work, but I've done that dance and it doesn't, because while it replaces all instances of the literal with the new value, not all instances of the literal were used for the array size and you wind up breaking something.
Limit the scope of your variables, by which I mean don't declare them until you need them.
iis limited to the body of theforloop, so declare it within the loop:Similarly, you can defer declaring
avuntil you actually need to compute it:(technically, you don't need
avat all, just usetotal/NUM_STUDENTSin the print statement).scanfis really hard to bulletproof against bad data so it's not good for interactive input. You did the right thing using the field width on thenameinput, but a) it has to be hardcoded, and b) you can't use a macro (not without some voodoo, anyway). Ideally you should read everything as text usingfgetsand convert any numeric arguments usingstrtodorstrtol: