Home

10 Tips and Reminders for C Programmers

|
|  Updated:  
2022-08-04 20:17:45
|   From The Book:  
No items found.
C All-in-One Desk Reference For Dummies
Explore Book
Buy On Amazon
It’s difficult to narrow down the list of reminders and suggestions, especially for a topic as rich and diverse as programming. For example, an expert could suggest ways to fit in with other programmers, which movies to quote, which games to play, and even which foods to eat. A programming subculture exists — even today, though the emphasis on professional workplace attire has thankfully abated.

C programming tips © Shutterstock/dotshock

Beyond social suggestions, there are a few things to remind you of — plus, some general-purpose C programming language recommendations. Believe it or not, every programmer has been through the same things you’ve experienced. It’s good to hear advice from a grizzled programming veteran.

Maintain good posture when you’re programming

Someone in your early life probably drilled into you the importance of having proper posture. Ignore them at your own peril, especially when you’re young and haven’t yet gotten out of bed to say, “Ouch.”

For many programmers, coding becomes an obsession. For most C programmers, it’s quite easy to sit and write code for many hours straight. Such a stationary position is hard on the body. So, every few minutes, take a break. If you can’t manage that, schedule a break. Seriously: The next time you compile, stand up! Look outside! Walk around a bit!

While you’re working, try as hard as you can to keep your shoulders back and your wrists elevated. Don’t crook your neck when you look at the monitor. Don’t hunch over the keyboard. Look out a window to change your focus.

Remember that it’s pleasant to acknowledge others. True, it’s easy to grunt or snarl at someone when you’re in the midst of a project. Keep in mind that other humans may not appreciate the depth of thought and elation you feel when you code. If you can’t be pleasant now, apologize later.

Use creative names in your C programs

The best code reads like a human language. It’s tough to make the entire source code read that way, but for small snippets, having appropriate variable and function names is a boon to writing clear code.

For example, the following expression is a favorite:

while(!done)
You can read this statement as “while not done.” It makes sense. Until the value of the donevariable is TRUE, the loop spins. But somewhere inside the loop, when the exit condition is met, the value of done is set equal to TRUE and the loop stops. It’s lucid.

It also helps to offer descriptive names to your C functions. A name such as setringervolume() is great, but the name set_ringer_volume() is better. It also helps to consider the function in context. For example:

ch=read_next_character();
In the preceding line, the function read_next_character() needs no explanation — unless it doesn’t actually return the next character.

Write a function in C

Anytime you use code more than once, consider throwing it off into a function, even if the code is only one line long or appears in several spots and doesn’t really seem function-worthy.

Suppose that you use the fgets() function to read a string, but then you follow fgets() with another function that removes the final newline character from the input buffer. Why not make both items their own function, something like get_input()?

Work on your C code a little bit at a time

A majority of the time you spend coding is to fix problems, to correct flaws in logic, or to fine-tune. When making such adjustments, avoid the temptation to make three or four changes at one time. Address issues one at a time.

The reason for the admonition is that it’s tempting to hop around your code and work on several things at a time. For example: You need to fix the spacing in a printf() statement’s output, adjust a loop, and set a new maximum value. Do those things one at a time!

When you attempt to do several things at a time, you can screw up. But which thing did you goof up? You have to go back and check everything, including the related statements and functions, to ensure they work. During situations like these, you will seriously wish for a time machine. Instead, just work on your code a little bit at a time.

Break apart larger C projects into several modules

No one likes to scroll through 500 lines of code. Unless you’re totally immersed in your project and can keep everything stored in your noggin, break out functions into modules.

Many C programmers prefer to group related functions into similar files. C programmers typically have an output file, an input file, an initialization file, and so on. Each file, or module, is compiled and linked separately to form the code. The benefits are that the files are smaller and if they compile and work, you no longer need to mess with them.

Know what a pointer is in C

A pointer is a variable that stores a memory location. It’s not magic, and it shouldn’t be confusing, as long as you keep the basic mantra in your head:

A pointer is a variable that stores a memory location.

A memory location stored in a pointer references another variable or a buffer (like an array). Therefore, the pointer must be initialized before it’s used:

A pointer must be initialized before it’s used.

When the pointer variable in C is prefixed by the *(asterisk) operator, it references the contents of the variable at the memory location. This duality is weird, of course, but it’s highly useful.

  • Declare a pointer variable by using the *
  • Use the & operator to grab the address of any variable in C.
  • Arrays are automatically referenced by their memory locations, so you can use an array name without the & prefix to grab its address.
  • “Address” and “memory location” are the same thing.

A great way to explore pointers is to use the Code::Blocks debugger; specifically, the Watches window.

Add white space before condensing your C code

C programmers love to bunch up statements, cramming as many of them as they can into a single line, such as
while(putchar(*(sample++)))
Admit it: Such a construction looks cool. It makes it seem like you really know how to code C. But it can also be a source of woe.

My advice: Split out the code before you condense it. Make liberal use of white space, especially when you first write the code. For example, the line

if( c != '\0' )
is easier to read than the line
if(c!='\0')
After you write your code with white space — or use several statements to express something — you can condense, move out the spaces, or do whatever else you like.

In C language source code, white space is for the benefit of human eyes. I admire programmers who prefer to use white space over cramming their code onto one line, despite how interesting it looks.

Know when if-else becomes switch-case

Many C programmers are big fans of the if-else decision tree, but they generally avoid stacking up multiple if statements. It usually means that the programming logic is flawed. For example:
if(something)
    ;
else if(something_else)
    ;
else(finally)
    ;
This structure is okay, and it’s often necessary to deal with a 3-part decision. But the following structure, which has been built by many budding C programmers, probably isn’t the best way to code a decision tree:
if(something)
    ;
else if(something_else_1)
    ;
else if(something_else_2)
    ;
else if(something_else_3)
    ;
else if(something_else_4)
    ;
else(finally)
    ;
Generally speaking, anytime you have that many else-if statements, you probably need to employ the switch-case structure instead. In fact this example is probably what inspired the switch-case structure in the first place.

Remember assignment operators in the C language

Though it’s nice to write readable code, one handy tool in the C language is an assignment operator. Even if you don’t use one, you need to be able to recognize it.

The following equation is quite common in programming:

a = a + n;
In C, you can abbreviate this statement by using an assignment operator:
a += n;
The operator goes before the equal sign. If it went afterward, it might change into a unary operator, which looks weird:
a =+ n;
So the value of variable a equals positive n? The compiler may buy that argument, but it’s not what you intended.

Also, don’t forget the increment and decrement operators, ++ and --, which are quite popular in loops.

When you get stuck, read your code out loud

To help you track down that bug, start reading your code aloud. Pretend that a programmer friend is sitting right next to you. Explain what your code is doing and how it works. As you talk through your code, you’ll find the problem. If you don’t, have your imaginary friend ask you questions during your explanation.

Don’t worry about going mental. You’re a C programmer. You’re already mental.

As a bonus, talking through your code also helps you identify which portions need to have comments and what the comments should be. For example:

a++;      /* increment a */
In the preceding line, you see a terrible example of a comment. Duh. Of course, a is incremented. Here’s a better version of that comment:
a++;      /* skip the next item to align output */
Don’t just comment on what the code is doing — comment on why. Again, pretend that you’re explaining your code to another programmer — or to future-you. Future-you will thank present-you for the effort.

Want to learn more? Check out our C Programming For Dummies Cheat Sheet.

About This Article

This article is from the book: 

No items found.

About the book author:

Dan Gookin has been writing about technology for 20 years. He has contributed articles to numerous high-tech magazines and written more than 90 books about personal computing technology, many of them accurate.
He combines his love of writing with his interest in technology to create books that are informative and entertaining, but not boring. Having sold more than 14 million titles translated into more than 30 languages, Dan can attest that his method of crafting computer tomes does seem to work.
Perhaps Dan’s most famous title is the original DOS For Dummies, published in 1991. It became the world’s fastest-selling computer book, at one time moving more copies per week than the New York Times number-one best seller (although, because it’s a reference book, it could not be listed on the NYT best seller list). That book spawned the entire line of For Dummies books, which remains a publishing phenomenon to this day.
Dan’s most recent titles include PCs For Dummies, 9th Edition; Buying a Computer For Dummies, 2005 Edition; Troubleshooting Your PC For Dummies; Dan Gookin’s Naked Windows XP; and Dan Gookin’s Naked Office. He publishes a free weekly computer newsletter, “Weekly Wambooli Salad,” and also maintains the vast and helpful Web site www.wambooli.com.