tracking if loops in C source code

tittu used Ask the Experts™
if decission construct in C code needs to be identified and
write to a separate file which displays only if loop ,
any example code or script for this in any language.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

a combination out of grep and awk maybe?

recognizing all the "if" possible structures in C is not simple.
you might need to write a parser, I think sed/awk options will fall short for this assignment.

writing a parser is not a an simple thing but if you really need one you can get several parser projects with source code at

I agree with pmasotta; to do what you want is not trivial and you should use a parser. If implementing what you need can be done in C you could take a look for existing flex/bison parser (i.e., if C++ with boost is an option you could use boost::spirit (i.e.

Here some other maybe helpful things:

JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.


any example using sed, awk bison or any script , regexp etc.

you won't find a 5 lines example on this...
your problem sounds very simple but it's not.

if you are serious about this assignment you probably have to emulate up to a certaint extent what every C/C++ compiler does.
Fortunatelly many of them are "open source"

This guy here gives you a landscape of the available resources to start with
Software Developer
You can simplify your problem by running GNU indent over your source files first. This will guarantee that indenting  of if constructs is correct. Given the right options, indent will place the trailing brace on a line by itself - that may not be the style you like, but it will make automatic processing easier. You need to look out for a following else at the same indentation . In the absence of braces, anything other than else or a trailing brace at the same indication indicates the end of if.
You might like to try my options in runindent (attached). Make it executable, then run it with 1 C file as its argument. (It only does 1 file at a time, but making it do multiple files would be easy).


not a full solution
Hm ...

@tittu: I think it's strange you accepted the one and only comment as answer which doesn't contain anything related to the original question (@duncan_roe: I don't want to decry your comment, such indentation for sure will make parsing the file easier - but the question was about parsing the code in any way).


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial