Jump to content

Like
0Likes
Dislike
Satan's Syntax


string code temporary sprintf function first template \\0' different
A lot of us picked up bad habits from our earlier days of coding that are still with us today. This article discusses how we can use some quirks of C's syntax to overcome these habits and write more efficient code.

4: Adsense

A lot of people code by example. This example becomes a template. Once the template is known, different variables, different values, and different functions are applied to the template and combined with glue code to implement the required solution. By being more aware of the syntax, much of this glue can be removed. This article illustrates a few quirks of the C syntax, and how it can be used (abused?) to implement more efficient code, without qualifying for the IOCCC (International Obfuscated C Code Contest)!


Remember The Return Types

My first example of this "template programming" will involve the formatting output function sprintf. It is not unusual to write code such as:

sprintf(str1, "Old v=%d\t",v);
/* Some code that plays with v */
sprintf(str2, "New v=%d",v);
strcat(str1, str2);
printf(str1);
Most instances of sprintf use a temporary string as the first parameter. This is the template that becomes engrained: "sprintf requires a temporary string". Whereas a better template would be a syntactical one, "sprintf requires a pointer to a character [. This is a reminder that we could, instead, use a function that returns a char * as our first parameter, saving a temporary buffer. For example:<br /><br />sprintf(str, "Old v=%d&#092]

About the Author(s)

After graduating with honours from Loughborough University, where he wrote his first compiler, Steven Goodwin took a temporary job writing computer games. Many years later, he's still doing it, finding more ways to manipulate the syntax than his colleagues would like! His computing interests include esoteric languages, code optimisation and automatic MIDI compositions. His interests outside of computing also use computers.

0 Comments

Note: GameDev.net moderates article comments.