simple tricks in c Programming-Tricks1
Tricks1
I have been in a fair number of programming courses in my life. Several of these have been in the hallowed C programming language. There was a time when C and C++ were the only languages I could call myself proficient in.
Over the years, I have seen
a constant pattern in all these courses - they teach you all the basics you
should learn, but none of what you will need. For instance, you have been
taught to use structures, but not much about how to use them to make sense of vile
madness that you might often encounter while coding in C. There is this neat
trick I will show you which uses structures and can really simplify working
with arrays. There’s something easy you can do with macros to make dynamic
allocations tons of times readable. And yes, there are amazing tools right
inside stdio.h which can make string
manipulation much easier. And you can use this trick to implement some radical
changes in the way you code C.
This is not an article for
professional C programmers. This is for Python and Javascript programmers who
would like to be able to really use C, the way they are used
to making their favourite languages do useful things.
Typedef the structs, unless it contains a
pointer to itself
Generally, when we work
with the struct datatype, we define the structures something
like this:
struct Position
{
double latitude;
double longitude;
double altitude;
};
And then we declare the
variables of this structure something like this:
struct Position
mypos;
I have no problem with this
- it is a classic method, something every good C programmers would know - but
must I place the struct keyword
twice here? Might I suggest a simple idiom for defining the structure which
changes the whole feel of the code to something more modern and less archaic?
typedef struct
{
double latitude;
double
longitude;
double altitude;
} Position;
And that is all. We do not
give the structure a name, but we use it as part of a typedef to make a new name for
the specific datatype which is this structure. Now, this is what the
declaration would look like:
Position mypos;
This is much more readable
to anyone who is more familiar with OOP code than with C code.
Comments
Post a Comment