View Poll Results: Which style of if do you use?

Voters
63. You may not vote on this poll
  • Style #1

    18 28.57%
  • Style #2

    37 58.73%
  • Style #3

    6 9.52%
  • Other

    3 4.76%
Multiple Choice Poll.

Which style of if loops is most common?

This is a discussion on Which style of if loops is most common? within the A Brief History of Cprogramming.com forums, part of the Community Boards category; i use k&r but generally add spaces in brackets, like: Code: if ( a ) { (TAB STROKE)i1; (TAB STROKE)i2; ...

  1. #16
    EOF
    Join Date
    Aug 2005
    Location
    Constanta, RO, Europe
    Posts
    46
    i use k&r but generally add spaces in brackets, like:

    Code:
    if ( a ) {
    (TAB STROKE)i1;
    (TAB STROKE)i2;
    (TAB STROKE)} else {
    (DOUBLE TAB STROKE)i3;
    (DOUBLE TAB STROKE)i4;
    (DOUBLE TAB STROKE)}
    (TAB STROKE)}
    i ussually use
    Code:
    if ( a ) i1 else i2;
    when using a single instruction. i edit my programs in notepad and prefer to see more of a "condensed" program than less of an "airy" one.

    this is an example:

    Code:
    /*
    ==============================================================================
    ===                                                                        ===
    === MNR source file - version 0.1 build 046 date 18.08.2005 test-c alpha-3 ===
    ===                        DOS/Windows and UNIX/Linux                      ===
    ===                                                                        ===
    ==============================================================================
    */
    
    #include "mnr.h"
    
    //prototypes
    char process_com(void);
    char test(void);
    void process(void);
    char cleanup(void);
    
    //global
    char *fis, *fos, *com, intr, dash, ign;
    FILE *fi, *fo, *dat;
    
    int main(int argc, char *argv[]) {
    	printf("\n\n\n===============================================================================\n");
    	printf("===              Welcome to the MNR Monstruous Numbers Reader               ===\n");
    	printf("===              version 0.1      copyright (C) 2005 moonlord               ===\n");
    	printf("=========== FOR TESTING AND EVALUATION ONLY - NOT FOR COMERCIAL USE ===========\n\n");
    	switch (argc) {
    		case 1: {
    			printf("=========== SYNTAX: \"MNR interpretation[switches] file_in file_out\" ===========\n");
    			printf("=== interpretation - \"a\" or \"b\" or \"c\" - according to whether the output is ===\n");
    			printf("===                  written in American, Britanic or Continental format    ===\n");
    			printf("===                  as described in the readme file.                       ===\n");
    			printf("=== switches - \"-\" to use dashes between word parts.                        ===\n");
    			printf("===          - \"i\" to ignore non-digit characters from file_in; an error is ===\n");
    			printf("===            generated otherwise.                                         ===\n");
    			printf("===   * switches are case-sensitive.                                        ===\n");
    			printf("=== file_in - the number is read from this file.                            ===\n");
    			printf("=== file_out - the text is written in this file.                            ===\n");
    			printf("===============================================================================\n\n");
    			return(0);
    			}
    		case 2: if (atol(argv[1]) == 443556) {printf(VERSTR); return(0);}
    				else {printf("ERR01: Syntax error.\n"); return(1);}
    		case 4: {
    			com=argv[1]; fis=argv[2]; fos=argv[3];
    			if(process_com()) {printf("ERR01: Syntax error.\n"); return(1);}
    			switch(test()) {
    				case 4: {printf("\nERR04: Error opening data file names.dat.\n"); return(4);}
    				case 3: {printf("\nERR03: Error opening output file %s.\n", argv[3]); return(3);}
    				case 2: {printf("\nERR02: Error opening input file %s.\n", argv[2]); return(2);}
    				case 1: {printf("\nAborted by user.\n"); return(0);}
    				}
    			if(count_file()) {printf("\nERR08: Non-digit character encountered.\n"); return(8);}
    	/**/		reopen_files();
    			process();
    			switch(cleanup()) {
    				case 3: {printf("\nERR07: Error closing data file names.dat.\n"); return(7);}
    				case 2: {printf("\nERR06: Error closing output file %s.\n", argv[3]); return(6);}
    				case 1: {printf("\nERR05: Error closing input file %s.\n", argv[2]); return(5);}
    				}
    			printf("Done.\n");
    			return(0);
    			}
    		default: {
    			 printf("ERR01: Syntax error.\n");
    			 return(1);
    			 }
    	}
    }
    
    
    //////////
    //
    // process_com(): Interpretes command.
    // Returns: 0 - success;
    //          1 - some syntax error;
    //
    
    char process_com(void) {
    	char *i=com;
    	switch(com[0]) {
    		case 'a': case 'b': case 'c': {intr=com[0];break;}
    		default: return(1);
    		}
    	while (*++i) {
    		switch(*i) {
    			case '-': {dash=1;break;}
    			case 'i': {ign=1;break;}
    			default: return(1);
    			}
    		}
    	return(0);
    }
    
    
    //////////
    //
    // test(): Tests and opens files (fi,fo,"names.dat").
    // Returns: 0 - success;
    //          1 - aborted by user;
    //          2 - error opening fi (input file);
    //          3 - error opening fo (output file);
    //          4 - error opening "names.dat";
    //
    
    char test(void) {
    	struct ffblk fot;
    	char conf;
    	if (!(findfirst(fos, &fot, 0) == -1)) {
    		do {
    			printf("%s already exists. Overwrite? (Y/N)", fos);
    			conf=toupper(getche());
    			printf("\n");
    		} while (conf != 'Y' && conf != 'N');
    		if (conf == 'N') return(1);
    	}
    	if ((fi=fopen(fis, "rt")) == NULL) return(2);
    	if ((fo=fopen(fos, "wt")) == NULL) return(3);
    	if ((dat=fopen("names.dat", "rt")) == NULL) return(4);
    	return(0);
    }
    
    
    //////////
    //
    // process(): Reads from fi, writes in fo.
    // Returns: nothing.
    //
    
    void process(void) {
    	;
    }
    
    
    //////////
    //
    // cleanup(): Writes buffers and closes files.
    // Returns: 0 - success;
    //          1 - error closing fi;
    //          2 - error closing fo;
    //          3 - error closing "names.dat";
    //
    
    char cleanup(void) {
    	if (fclose(fi) == EOF) return(1);
    	if (fclose(fo) == EOF) return(2);
    	if (fclose(dat) == EOF) return(3);
    	return(0);
    	}
    it actually does nothing but is in progress. Will announce when it's ready if you're interested...
    Two strings walk into a bar. The first one says, 'Bartender! Bartender! I want a drink!'. The second one says, 'Bartender! Bartender! I want a drink too! Blaaaaaaaaah eeeeeeeek yaaaaaaak oooooooh'. The first one says, 'Please excuse my friend. He isn't null term--'.

  2. #17
    Supermassive black hole cboard_member's Avatar
    Join Date
    Jul 2005
    Posts
    1,709
    I like to use spaces before and after brackets:
    Code:
    void foo (void);
    if (a > b) {
    
    } else {
    
    }
    Just thought I'd add that from my previous post
    Good class architecture is not like a Swiss Army Knife; it should be more like a well balanced throwing knife.

    - Mike McShaffry

  3. #18
    ~viaxd() viaxd's Avatar
    Join Date
    Aug 2003
    Posts
    246
    i use Allman.

    moonlord, does this compile? i think the "t" mode in fopen is not standard:
    Code:
    	if ((fi=fopen(fis, "rt")) == NULL) return(2);
    	if ((fo=fopen(fos, "wt")) == NULL) return(3);
    	if ((dat=fopen("names.dat", "rt")) == NULL) return(4);
    :wq

  4. #19
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,220
    Quote Originally Posted by ahluka
    I like to use spaces before and after brackets:
    Code:
    void foo (void);
    if (a > b) {
    
    } else {
    
    }
    Just thought I'd add that from my previous post

    Oh I use spaces after control keywords like if, else and case but not after normal functions.

    Code:
    void blah(int foo)
    {
        if (foo == 3) {
           bar(foo);
        } else {
           bar(foo * 2);
        }
    }
    In fact this is pretty much the style I use:
    http://pantransit.reptiles.org/prog/CodingStyle.html

  5. #20
    Even death may die... Dante Shamest's Avatar
    Join Date
    Apr 2003
    Location
    Malaysia
    Posts
    970
    Brackets are for losers! Real men use commas!

    Code:
    #include <stdio.h>
    
    int main()
    {
      if ( true )
        printf( "Brackets " ),  
        printf( "are " ),
        printf( "for " ),
        printf( "losers!\n" ) ;
      else
        printf( "Commas " ),  
        printf( "are " ),
        printf( "for " ),
        printf( "winners!\n" ) ;
        
      getchar() ;
    }

  6. #21
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    In fact this is pretty much the style I use:
    http://pantransit.reptiles.org/prog/CodingStyle.html
    Hmm... The dude that made those coding style guidelines makes some rather dubious claims... though his style is pretty nice. It is pretty close to what I use when writing C, but my C++ code is always Allman unless I am writing a very small demo program for someone... then I take liberties.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  7. #22
    Banned
    Join Date
    Jun 2005
    Posts
    594
    im like dave and perspective, i like to use allman, with the extra spaces.

  8. #23
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    I mostly use:
    Code:
    if (x == y  ||  z == w) {
        puts("Whatever.");
        puts("Seriously.");
    } else {
        puts("Okay...");
        puts("yah.");
    }
    Sometimes I'll use
    Code:
    if (x == y  ||  z == w) { puts("Whatever.");
                              puts("Seriously.");
                            }
                       else { puts("Okay...");
                              puts("yah.");
                            }
    But I've only done that sort of thing in Perl. (Usually only when mixing a bunch of one-line anonymous subroutines with multi-line anonymous subroutines.)

    Double spaces around || and && are important to me.

  9. #24
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640
    >>Double spaces around || and && are important to me.

    why, they have no intrinsic value except to fool you into thinking your logic is correct when it might not be. Your better off using extra brackets IMHO.

    if ((x == y) || (z == w)) {

  10. #25
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    The only purpose of those parentheses is visual, and since parentheses do me more muddling than clarifying, double spaces are better.

    How could double spaces fool me into thinking my logic is correct?

  11. #26
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Location
    Australia
    Posts
    986
    That GNU one has to be the ugliest style ever. Also it would have to be the slowest - space space {, enter tab <code> as opposed to {, enter tab code. Also most IDE's auto indent now too, so you'd have to backspace the tab and space twice again. Yuck!

  12. #27
    ---
    Join Date
    May 2004
    Posts
    1,379
    Dev-C++ auto indents to K&R even though it uses a GNU compiler.

  13. #28
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>Also most IDE's auto indent now too, so you'd have to backspace the tab and space twice again.<<
    Just change the IDE's config to use spaces instead of tabs upon invoking the auto-indent (assuming its available).


    I look after code that is quite old (been running for 10 years+), and many people have changed it over this period of time. Some have used tabs (a mixture of one tab, two tabs, even four tabs for indentation), and some have used spaces (again, varying numbers). It's a mess, and is really aweful to look at sometimes.
    My advice: Whatever your own personal preference, if you're amending someone else's code, use their style of indentation and bracketing in preference to your own. That way, future generations of programmers will at least see a common approach throughout.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  14. #29
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640
    Quote Originally Posted by Rashakil Fol
    The only purpose of those parentheses is visual
    In that case yes, but in the general case thats not true.

    Quote Originally Posted by Rashakil Fol
    How could double spaces fool me into thinking my logic is correct?
    you use spaces to group your logic, but spaces have no effect on syntax, brackets do. If you group your logic using brackets, you know it will execute the way you've intended it to. If you group your logic with spaces, it will execute based on order of operations despite what the visual cues of your spaces suggest.

    ex:
    if (a && b || c)

    is that if ((a && b) || c) or if (a && (b || c)).

  15. #30
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    Quote Originally Posted by Perspective
    you use spaces to group your logic, but spaces have no effect on syntax, brackets do. If you group your logic using brackets, you know it will execute the way you've intended it to. If you group your logic with spaces, it will execute based on order of operations despite what the visual cues of your spaces suggest.
    Obviously, if parentheses are needed, then in the spirit of not-being-a-moron, they are written. However, in the case of
    Code:
    (x == y  ||  z == w)
    , they are not needed.


    Quote Originally Posted by Perspective
    ex:
    if (a && b || c)

    is that if ((a && b) || c) or if (a && (b || c)).
    I see nothing wrong with
    Code:
    ((a  &&  b)  ||  c)
    .

    But this would be if a and b and c are expressions. If a and b are simply integral values, then
    Code:
    ((a && b)  ||  c)
    might be used.
    Last edited by Rashakil Fol; 08-21-2005 at 09:53 PM.

Page 2 of 3 FirstFirst 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to handle multiple cases which use common code?
    By tmaxx in forum C Programming
    Replies: 3
    Last Post: 10-03-2008, 07:42 AM
  2. WM_CAPTION causing CreateWindowEx() to fail.
    By Necrofear in forum Windows Programming
    Replies: 8
    Last Post: 04-06-2007, 08:23 AM
  3. Button handler
    By Nephiroth in forum Windows Programming
    Replies: 8
    Last Post: 03-12-2006, 05:23 AM
  4. WS_EX_COMPOSITED style (double buffering) problems
    By JasonD in forum Windows Programming
    Replies: 2
    Last Post: 10-12-2004, 11:21 AM
  5. Tab Controls - API
    By -KEN- in forum Windows Programming
    Replies: 7
    Last Post: 06-02-2002, 09:44 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21