Tuesday 3 September 2013

Use Indent to indent your C-code

I myself not very much expert in writing indented code and code without indentation looks just horrible. Of course you will not have same feelings if you are using an IDE with auto indentation facility and of course if you know how to write indented code. For this purpose I found Indent command very useful in linux. One thing you should remember that this command is only for C code.
Actually not me, one of my friend Arjun Pakrashi informed me about this command.
What the command does is it changes the appearance of a C program by inserting or deleting whitespace.
Syntax of the command is like:

indent [options] [input-files] or
indent [options] [single-input-file] [-o output-file]

Indent command provided many options to format the source file like :-

[-bad] : Force blank lines after the declarations.
[-npcs] : Do not put space after the function in function calls.
[-nsaw] : Do not put a space after every while etc.

Actually I too haven't used all the options provided by the command. I only use the -linux command that converts the source c file to linux coding style.
There are many style that you can follow to indent like :-

[-gnu] : Use GNU coding style.  This is the default.
[-kr] : Use Kernighan & Ritchie coding style. etc.

I will provide a sample unindented code to show how it converted to an indented one.

Unindented code:-
#include<stdio.h>
int main()
{int a,b,c;
printf("Enter two numbers:");
scanf("%d,%d",&a,&b);
c=a+b;
printf("Sum of %d and %d is:%d\n",a,b,c);
return 0;
}

After executing the following command I got the output.
 
indent -linux input.c -o output.c

Indented code:-

#include<stdio.h>

int main()
{
    int a, b, c;
    printf("Enter two numbers:");
    scanf("%d,%d", &a, &b);
    c = a + b;
    printf("Sum of %d and %d is:%d\n", a, b, c);
    return 0;
}

2 comments:

  1. very helpfull information..... :)

    ReplyDelete
  2. I generally use default configuration with the -nut switch. This will replace the tab characters with blankspaces. Helps when copy-pasting a code into HTML WYSIWYGs or other places where tablength is different.

    ReplyDelete