Actions

EmSys

CCoding Style - Use else-ifs for multi-way decisions

From EdWiki

Revision as of 09:30, 23 June 2015 by Jshankar (Talk | contribs) (1 revision imported: EdWiki -- Emsys pages from Shukra)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Use else-ifs for multi-way decisions

A sequence of nested if statements is often a warning of awkward code, if not outright errors:

If( argc == 3 )
    if( ( fin = fopen( argv[1], “r”) ) != NULL )
        if( ( fout = fopen( argv[2], “w”) ) != NULL ) {
            while( ( c = getc(fin) ) != EOF )
	        putc(c, fout);
	fclose(fin); fclose(fout);
        } else printf( “Can’t open output file %s\n”, argv[2] );
    else printf( “Can’t open input file %s\n”, argv[1] );
else printf( “Usage : cp inputfile outputfile\n” );