Tagged: c Toggle Comment Threads | Keyboard Shortcuts

  • ThomasPowell 5:11 pm on December 27, 2014 Permalink
    Tags: c, , smalltalk, style   

    Programming Style: Language Specific Domains 

    My Beginner and C Days

    The visual presentation of the code has mattered to me, from the first days I wrote C code in Microsoft editor. In those days, it was a Microsoft C 5.0 IDE on either DOS or OS/2.

    #include "stdio.h"
    	int rows,columns,ROW, COLUMN;
    	scanf("%d %d",&ROW,&COLUMN);
    	rows = 0;
    	columns = 0;
    	while(columns++ < COLUMN)
    	rows += 1;
    	while(rows++ < (ROW - 2)){
    		columns = 0;
    		while(columns++ < (COLUMN - 2)){
    			printf(" ");
    	columns = 0;
    	while(columns++ < COLUMN) {

    Ok, not *that* far back, but I did have strong opinions about C from the early days of my being paid to program in it:

    • TABS, not spaces
    • 3 (in Microsoft land) spaces per tab (eventually switched to 4)
    • always include braces for if clauses
    • generally no parentheses for return values
    • ternary operator GOOD

    That made the code look like this (except that tabs are tabs in pre blocks).

    int compare(const void *a, const void *b)
    	return(strcmp(*(char **)a, *(char **)b));
    int checkDictionary(char *word)
    	if(bsearch((void *)&word, (void*)dictionary, wordCount, sizeof(char *), compare))
    		return 1;
    	return 0;

    But I remember so much variation in coding style preferences, as evidenced by the Indent Style article on Wikipedia. Everyone had their own preferred style, and everyone had their own preference for how much everyone else should adhere to a common style. On one team I worked, they eventually developed code reviews which were nothing more than berating people for not adhering to an arbitrary style guide: an in-house version Hungarian Notation, exactly one return per function, etc.

    Java and Perl days

    In Java land, my preference for camelCasing was reaffirmed. Working with Perl and Java, I eventually started putting the opening brace on the same line as if statements and function declarations.

    if(iAmAChangedProgrammer) {

    I think the brace thing was a result of a block that evaluated differently in awk or perl if it didn't hug the clause. I don't remember, but from that point on, I was convinced of that way being the only way.


    Coming into ruby has been interesting. Multiple returns (which never bothered me) are common. Implicit returns are the norm as well. There's a style guide which, for the most part, experienced rubyists adhere to (even if there are slight variations in practice). I find some disagreement with some of the style recommendations (I think I have found legit use for and over &&, etc...), but I'm happy to fall in line with the style recommendations and help enforce them.

    Some of the styles have obvious purpose, but some seem rather arbitrary. Why are guard clauses so accepted in Ruby when C was so scared of them, etc...


    In reading Smalltalk Best Practice Patterns, it all came together.

    As part of the style guide near the end of the book, the author talks about using the line-wrapping of the browser window to naturally wrap argument lists instead of taking up vertical space with them. That's when it dawned on me how much preferences in code styles also come from the languages that influenced the current language.

    Ruby's heritage from Smalltalk means that it carried forward that aversion to deep nesting that performs poorly in small code browser windows (even in Squeak and Pharo, the code windows can get pretty tiny.)

    C coders may have come from GOSUB type languages where there truly was only one return (unless an IF clause buried another) and there could be multiple entry points. Multiple entry and exit point aversion came from languages in which you could GOSUB to anywhere before a RETURN statement, and a nested RETURN could be harder to detect than one on the main logic level.


    Early language coding styles likely came from specific pain points experienced by a prior guru and then arbitrarily passed along because "We've always done it that way." At some point, tasks and readable code become hindered by following rules that we don't have a rationale behind.

    Community style guides hopefully have the benefit of thousands of years of cumulative experience in challenges and best practices collaborating on equal footing, but that assumes that we're not just agreeing with our technical elders because that's the way it's always been done.

    Try to understand the problem domain of coding in a specific language as it relates to coding style. Maybe your coding style thinks its still programming in COBOL or BASIC.

  • tech0x20 9:41 pm on June 4, 2012 Permalink | Reply
    Tags: c   

    Naive palindrome substring check written in C. 

    Below is a quick and naive implementation of a palindrome substring checker written in C. All characters are considered part of the palindrome (i.e. whitespace and punctuation is not filtered out). Substrings of larger palindromes are also printed separately.

     * printPalindromes - prints all palindromes in 
     *  a string, including substrings of larger 
     *  palindromes. Treats all characters as 
     *  a valid palindrome character, including 
     *  whitespace and punctuation.
    void printPalindromes(char *inputString) {
        int center;
        int offset;
        int length = strlen(inputString);
        /* odd-sized palindrome is a minimum 3 characters,
         * so center must at least be 1 more than 0, and 
         * must be at least 1 space from the last element.
         * left side: center - offset
         * right side: center + offset
        for(center = 1; center < length - 2; center++) {
          for (offset = 1; 
              center + offset < length 
              && center - offset >= 0
              && inputString[center + offset] == inputString[center - offset];
              offset++) {
            // print subString from center - offset to center + offset
            printf("%.*sn", offset * 2 + 1, &inputString[center - offset]);
        /* even-sized palindrome is a minimum of 2 characters
         * (the center). Center and center + 1 must match for even
         * length
        for(center = 0; center < length - 3; center ++) {
          if(inputString[center] != inputString[center + 1]) {
          /* we know this matches by default */
          printf("%.2sn", &inputString[center]);
          /* offsets on the right side are one over because "center"
           * is actually 2 characters.
           * left side: center - offset
           * right side: center + offset + 1
          for(offset = 1;
              center + offset + 1 < length
              && center - offset >= 0
              && inputString[center + offset + 1] == inputString[center - offset];
              offset ++) {
            // print subString from center - offset to center + offset + 1
            printf("%.*sn", offset * 2 + 2, &inputString[center - offset]);
    int main(int argc, char **argv) {
      int arg;
      for(arg=1; arg < argc; arg++) {

    Example results:

    CostaRica:c thomaspowell$ ./palindromes "why forerof baad baab ddi"
    d baab d
  • tech0x20 3:53 pm on March 21, 2011 Permalink | Reply
    Tags: c, , ,   

    Date formatting for Single Unix Specification(R) versions of “date” 

    The date command is wonderful for formatting dates, as such

    date --date="2010-01-01" +%Y%j

    But what happens when you’re on a system whose date command only supports the -u [UTC] and + [for formatting] options?

    Below is a quick hack in straight C that provides the ability to format a date that you provide. This is ideal if your unix install of perl is very basic or non-existent, but you still have access to the C compiler.

    Compiling the target would go as follows:

    gcc strptime.c -o strptime

    Running the output would be as follows:

    ./strptime "2010-01-01" "%Y%j"

    strptime.c source code–Please note: there is limited error checking for the wrong arguments, etc., and overlapping a built-in name such as strptime() isn’t the best of practices…

    int main(int argc, char *argv[]) {
        struct tm tm;
        time_t t;
        char string[255];
        if(strptime(argv[1], "%Y-%m-%d", &tm) == NULL) {
            if (strptime(argv[1], "%m/%d/%Y", &tm) == NULL ) {
                fprintf(stderr, "format errorn");
                return 1;
        strftime(string, sizeof(string) - 1, argv[2], &tm);
        return 0;
Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc
%d bloggers like this: