|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
I want to know the best practice to write on both C / C++ source codes.
The best practice is to ensure readable. Should left brace be after function or if on the same line or next line. For example... void Test( void) { int a = 5; printf( "%d\n", a); } or... void Test( void) { int a = 5; printf( "%d\n", a); } It applies to if. For example... if (a == 5) { printf( "%d\n", a); printf( "End...\n"; } or... if (a == 5) { printf( "%d\n", a); printf( "End...\n"; } -- Yours Truly, Bryan Parkoff |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
"Bryan Parkoff" <nospam@nospam.com> writes:
>I want to know the best practice to write on both C / C++ source codes. I do not know what the best practice is. When in doubt, it might be a neutral choice to format as in the C specification, i.e., #include <fenv.h> void f(double x) { #pragma STDC FENV_ACCESS ON void g(double); void h(double); /* ... */ g(x + 1); h(x + 1); /* ... */ } However, my personal style differs from this and is being described below with a rationale for it. One Way to Format Parentheses There are several different ways to format texts with braces and parentheses. One of them is being described here. Indentation within Braces An indentation of just one space often is too small to be seen clearly, because the natural width and form of characters often varies by an amount that is not very much smaller than a space. Therefore, the indentation should amount to at least two positions. In order not to waste horizontal spaces, an indentation of exactly two positions is chosen. This means, that the left position of the next level is two larger than the position of the directly enclosing level. Indentation by two positions within a block { ++x; ++x; } ^ ^ 0 2 Bad: A small indentation by one position is not always visible clearly {++x; ++x; } Good: The indentation by two positions is visible clearly { ++x; ++x; } Bad: A large indentation by more than two positions wastes horizontal space with no additional benefit { ++x; ++x; } Spaces within braces In mathematics, there are often no spaces at the inner side of parentheses or braces in expressions, but spaces are used indeed at the inner side of braces in set notation, when the braces contain a description (not when they contain a list). Spaces in set notation { x | x > 2 } This style is adopted here: One space is written at the inner side of braces. Spaces at the inner side of parentheses within a block { ++x; } This style is consistent with the indentation by two positions, because only using this style, corresponding parts of two lines have the same position. Bad: No space after the first brace, the two statements are misaligned {++x; ++x; } Good: One space after the first brace, the two statements are properly aligned { ++x; ++x; } Bad: Two spaces after the first brace, the two statements are misaligned { ++x; ++x; } There are some exceptions to this rule: No spaces are used within empty braces "{}" and between two or more closing braces of the same direction "}}", except, when the first one of them is part of an empty pair "{} }" (an empty pair of braces if treated like a single non-braces character). Unified rules for all Brackets For simplicity and uniformity, the rules from above apply to all kinds of brackets, including parentheses, braces (curly brackets), square brackets, and angle brackets. Spaces within parentheses and square brackets { y = f( x )+ g() + a[ 2 ]; } Binary operators are sorrounded by a space, but the space is omitted, when there already is a space on the other side of a sequence of brackets directly beside the operator: By this rule, " )+" is written instead of " ) +". Representation of the Syntactical Structure A function declaration in C consists of a head and a body. The following representation shows this structure: Good formatting according to the structure void alpha() // head { beta(); } // body The following formatting is misleading, because the line break does not match the structural break: Bad line break within the body void alpha() { // head and the beginning of the body beta(); } // the rest of the body This formatting also would make no sense for blocks within blocks. So it is often not used for such blocks. Therefore even the adopters of this style can not use it uniformly. Opening Braces Look Like "bullets" There is a well known style to publish lists in typography using bullets sticking out on the left, looking like this: Common list representation with bullets in typography o This is the first point of this list, it is written here just as an example. o Here is another entry o This is another example given just as an example to show an example The braces of the beginnings of blocks stand out on the left just the same, when the formatting being described here is used, so they look quite naturally as beginning-of-a-block markers, when one is used to the typographical list notation: Left braces look like bullets to mark blocks { printf(); printf(); printf(); printf(); printf(); printf(); printf(); } { printf(); printf(); } { printf(); printf(); printf(); printf(); printf(); printf(); } Neutrality Someone wrote this C code: while( fgets( eingabe, sizeof eingabe, stdin )) if( sscanf( eingabe, "%d", &wert )!= 1 ) fprintf( stderr, "Please enter a number!\n" ); else summe += wert; It amazes me that I can add braces by my style conventions (not changing the meaning of the code) without the need to change the position of any character of the given code or change the overall number of line: The code from above plus braces while( fgets( eingabe, sizeof eingabe, stdin )) { if( sscanf( eingabe, "%d", &wert )!= 1 ) { fprintf( stderr, "Please enter a number!\n" ); } else { summe += wert; }} Insofar, my bracing style might be considered non-obtrusive. See also: http://www.purl.org/stefan_ram/pub/c_format_en |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
Bryan Parkoff wrote:
> I want to know the best practice to write on both C / C++ source codes. > The best practice is to ensure readable. Should left brace be after > function or if on the same line or next line. LOL. |
|
|
|
#4 |
|
Messages: n/a
Hébergeur: |
On 2008-04-05 22:11, Bryan Parkoff wrote:
> I want to know the best practice to write on both C / C++ source codes. > The best practice is to ensure readable. Should left brace be after > function or if on the same line or next line. The best style is the one that is used in the code you are working in. If you are starting from scratch use whatever your IDE uses. Don't spend a lot of time on indentation and such, for most people it really does not matter once they get used to a style. I'll say this though, monitors are getting quite large these days and whitespace is cheep, your goal should always be to keep your code as readable as possible. -- Erik Wikström |
|
|
|
#5 |
|
Messages: n/a
Hébergeur: |
On 5 Apr., 22:11, "Bryan Parkoff" <nos...@nospam.com> wrote:
> I want to know the best practice to write on both C / C++ source codes. > The best practice is to ensure readable. Should left brace be after > function or if on the same line or next line. This is a matter of personal preference in study programs or homebrew code. In commercial projects there is usually a company coding guide that defines this kind of stuff. It is not so important what style you decide on, it is important that every developer working on one code base uses the same style. best, Michael |
|
|
|
#6 |
|
Messages: n/a
Hébergeur: |
Bryan Parkoff wrote:
> I want to know the best practice to write on both C / C++ source > codes. The best practice is to ensure readable. Should left brace be > after function or if on the same line or next line. > > For example... > > void Test( void) { > int a = 5; > printf( "%d\n", a); > } > > or... > > void Test( void) > { > int a = 5; > printf( "%d\n", a); > } > > It applies to if. For example... > > if (a == 5) { > printf( "%d\n", a); > printf( "End...\n"; > } > > or... > > if (a == 5) > { > printf( "%d\n", a); > printf( "End...\n"; > } Personal choice. Whatever you are comfortable with. When working with existing code it's probably a good idea to stick with the formatting it uses. Personally, I use the 2nd format of { on it's own line. My IDE prefers that format too and some auto formatting gets screwed up if it isn't in that format. -- Jim Langston tazmaster@rocketmail.com |
|
|
|
#7 |
|
Messages: n/a
Hébergeur: |
On 5 avr, 22:11, "Bryan Parkoff" <nos...@nospam.com> wrote:
> I want to know the best practice to write on both C / C++ source codes.. > The best practice is to ensure readable. Should left brace be after > function or if on the same line or next line. In the case of a function or a class, I'd say that there are significant technical arguments for requiring 1) the opening left brace on a line by itself, in column one, and 2) in the case of functions, putting the return type on a line by itself, above the function. (The idea is that the name, qualified by the class if it is a member function, start in column 1.) > For example... > void Test( void) { > int a = 5; > printf( "%d\n", a); > } > or... > void Test( void) > { > int a = 5; > printf( "%d\n", a); > } > It applies to if. For example... > if (a == 5) { > printf( "%d\n", a); > printf( "End...\n"; > } > or... > if (a == 5) > { > printf( "%d\n", a); > printf( "End...\n"; > } In this case, it really doesn't matter. Choose one, and stick to it. (I would say that if the opening brace is on the same line, you should require it always. I'd also require it always in the other case, but it's less critical, since it is readily apparent if it is missing.) -- James Kanze (GABI Software) email:james.kanze@gmail.com Conseils en informatique orientée objet/ Beratung in objektorientierter Datenverarbeitung 9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34 |
|
|
|
#8 |
|
Messages: n/a
Hébergeur: |
On 5 avr, 23:36, Erik Wikström <Erik-wikst...@telia.com> wrote:
> On 2008-04-05 22:11, Bryan Parkoff wrote: > > I want to know the best practice to write on both C / C++ > > source codes. The best practice is to ensure readable. > > Should left brace be after function or if on the same line > > or next line. > The best style is the one that is used in the code you are > working in. If you are starting from scratch use whatever > your IDE uses. Do IDE's impose a style? Or even default to one? The editors I use don't normally break a line just because you enter a brace; if the brace is to be on a line by itself, you have to enter the newline manually. (The editors do indent the next line according to their idea of where it should be indented. I find this mainly useful because if their idea of where it should be isn't the same as mine, it often means I've forgotten to close a parentheses.) > Don't spend a lot of time on indentation and such, for most > people it really does not matter once they get used to a > style. Within limits, and as long as it is consistent. (I'm old enough to remember when no indentation was the most common style, every line starting in column 1. Or column 7. No thank you.) > I'll say this though, monitors are getting quite large these > days and whitespace is cheep, your goal should always be to > keep your code as readable as possible. I don't understand the issue about white space. If you have to indent more than three levels, for whatever reason, there's something wrong. The monitor width is potentially valid with regards to symbol length, but you shouldn't neglect the fact that you might want to have a listing; I'd argue that the lines should be short enough to fit horizontally on a page of A4 paper, in portrait mode, with a readable sized font. -- James Kanze (GABI Software) email:james.kanze@gmail.com Conseils en informatique orientée objet/ Beratung in objektorientierter Datenverarbeitung 9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34 |
|
|
|
#9 |
|
Messages: n/a
Hébergeur: |
James Kanze wrote:
> On 5 avr, 22:11, "Bryan Parkoff" <nos...@nospam.com> wrote: >> I want to know the best practice to write on both C / C++ source codes. >> The best practice is to ensure readable. Should left brace be after >> function or if on the same line or next line. > > In the case of a function or a class, I'd say that there are > significant technical arguments for requiring 1) the opening > left brace on a line by itself, in column one, and 2) in the > case of functions, putting the return type on a line by itself, > above the function. (The idea is that the name, qualified by > the class if it is a member function, start in column 1.) While I prefer the above on a readibility/cosmetic pov, I don't think I've ever seen an actual technical argument other than it makes finding functions easier when searching by way of regular expressions. Is that the reason or are there other justifications? <bracing examples snipped> |
|
|
|
#10 |
|
Messages: n/a
Hébergeur: |
On Apr 7, 2:33 am, stan <smo...@exis.net> wrote:
> James Kanze wrote: > > On 5 avr, 22:11, "Bryan Parkoff" <nos...@nospam.com> wrote: > >> I want to know the best practice to write on both C / C++ source codes. > >> The best practice is to ensure readable. Should left brace be after > >> function or if on the same line or next line. > > In the case of a function or a class, I'd say that there are > > significant technical arguments for requiring 1) the opening > > left brace on a line by itself, in column one, and 2) in the > > case of functions, putting the return type on a line by itself, > > above the function. (The idea is that the name, qualified by > > the class if it is a member function, start in column 1.) > While I prefer the above on a readibility/cosmetic pov, I > don't think I've ever seen an actual technical argument other > than it makes finding functions easier when searching by way > of regular expressions. Is that the reason or are there other > justifications? That's the reason. You can search for the definition, without getting any non-definition use. Also, vi uses a { in column one to recognize the start of a function body, and in practice, there'll be times that you'll have to edit with vi (or ed, which follows the same rules). -- James Kanze (GABI Software) email:james.kanze@gmail.com Conseils en informatique orientée objet/ Beratung in objektorientierter Datenverarbeitung 9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34 |
|
|
|
#11 |
|
Messages: n/a
Hébergeur: |
James Kanze wrote:
> On Apr 7, 2:33 am, stan <smo...@exis.net> wrote: >> James Kanze wrote: >> > On 5 avr, 22:11, "Bryan Parkoff" <nos...@nospam.com> wrote: >> >> I want to know the best practice to write on both C / C++ source codes. >> >> The best practice is to ensure readable. Should left brace be after >> >> function or if on the same line or next line. > >> > In the case of a function or a class, I'd say that there are >> > significant technical arguments for requiring 1) the opening >> > left brace on a line by itself, in column one, and 2) in the >> > case of functions, putting the return type on a line by itself, >> > above the function. (The idea is that the name, qualified by >> > the class if it is a member function, start in column 1.) > >> While I prefer the above on a readibility/cosmetic pov, I >> don't think I've ever seen an actual technical argument other >> than it makes finding functions easier when searching by way >> of regular expressions. Is that the reason or are there other >> justifications? > > That's the reason. You can search for the definition, without > getting any non-definition use. Also, vi uses a { in column one > to recognize the start of a function body, and in practice, > there'll be times that you'll have to edit with vi (or ed, which > follows the same rules). While I've been there, writing code with ed seems a little too manly ![]() While I'm primarily an emacs type, I use vim enough to get by and others sometimes but I'm not a vim guru. Thinking about it, I don't actually remember ever using an actual vi. I read that it's real hard/impossible to create a LALR or even yacc compatible grammer for c or c++. I've never sat down to try but my understanding is there are dark corners that cause problems. Is It possible to write a yacc grammer that simply recognizes function and class definitions? I know there are programs that detect functions but I believe they all do some clever pattern matching; I'm not aware of any that try actually parsing. |
|
|
|
#12 |
|
Messages: n/a
Hébergeur: |
On Apr 8, 1:27 am, stan <smo...@exis.net> wrote:
> James Kanze wrote: > > On Apr 7, 2:33 am, stan <smo...@exis.net> wrote: > >> James Kanze wrote: > >> > On 5 avr, 22:11, "Bryan Parkoff" <nos...@nospam.com> wrote: > >> >> I want to know the best practice to write on both C / > >> >> C++ source codes. The best practice is to ensure > >> >> readable. Should left brace be after function or if on > >> >> the same line or next line. > >> > In the case of a function or a class, I'd say that there are > >> > significant technical arguments for requiring 1) the opening > >> > left brace on a line by itself, in column one, and 2) in the > >> > case of functions, putting the return type on a line by itself, > >> > above the function. (The idea is that the name, qualified by > >> > the class if it is a member function, start in column 1.) > >> While I prefer the above on a readibility/cosmetic pov, I > >> don't think I've ever seen an actual technical argument other > >> than it makes finding functions easier when searching by way > >> of regular expressions. Is that the reason or are there other > >> justifications? > > That's the reason. You can search for the definition, without > > getting any non-definition use. Also, vi uses a { in column one > > to recognize the start of a function body, and in practice, > > there'll be times that you'll have to edit with vi (or ed, which > > follows the same rules). > While I've been there, writing code with ed seems a little too manly ![]() You should have used the editor on the original Intel development systems, then. After that, ed seems like something for sissies. (The basic philosphy was something like ed, but it allowed multiple commands on the same line, with constructs for looping, etc. A typical command line looked a bit like transmission noise, and an error in a single character could wreck havoc in your file.) Seriously, I don't think I've used ed much except for very small editing jobs in a script. > While I'm primarily an emacs type, I use vim enough to get by > and others sometimes but I'm not a vim guru. Thinking > about it, I don't actually remember ever using an actual vi. I still use it fairly often. Or production machines have a very limited environment, and we're not allowed to install just anything on them. > I read that it's real hard/impossible to create a LALR or even > yacc compatible grammer for c or c++. That's actually true for a lot of languages---even Pascal. The C/C++ declaration syntax, however, seems to be designed intentionally to make parsing difficult. > I've never sat down to try but my understanding is there are > dark corners that cause problems. Is It possible to write a > yacc grammer that simply recognizes function and class > definitions? If you're handling pre-processed input (or don't mind screwing up if someone was stupid enough to use the preprocessor in a way that messed with this), you can come pretty close with just regular expressions and a state machine. If you're interested, you might look at the code for my kloc program (http://kanze.james.neuf.fr/code-en.html, then look for kloc in the Exec directory). It collects a number of statistics (more or less accurately), such as the number of functions and the number of class definitions (those should be very accurate). It uses only lex and a very simple state machine; I won't say that it can't be fooled, but it does seem to work most of the time. (I think. It's really very old code, and I've not really verified it with templates. I did expand it to handle namespaces, but I wouldn't be surprised if it didn't get confused by template definitions which contain parentheses.) > I know there are programs that detect functions but I believe > they all do some clever pattern matching; I'm not aware of any > that try actually parsing. Any opening brace at namespace scope is either a class or a function definition. Knowing that you're at namespace scope The syntax for opening a namespace scope is pretty simple, so you should be able to track those (supposing no messing around with the preprocessor, of course) and `extern "C"' blocks. After that, any opening brace at namespace scope is the start of either a function, a class or an enum definition. -- James Kanze (GABI Software) email:james.kanze@gmail.com Conseils en informatique orientée objet/ Beratung in objektorientierter Datenverarbeitung 9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34 |
|
|
|
#13 |
|
Messages: n/a
Hébergeur: |
James Kanze wrote:
> On Apr 8, 1:27 am, stan <smo...@exis.net> wrote: >> James Kanze wrote: >> > On Apr 7, 2:33 am, stan <smo...@exis.net> wrote: >> >> James Kanze wrote: <snip> >> >> While I prefer the above on a readibility/cosmetic pov, I >> >> don't think I've ever seen an actual technical argument other >> >> than it makes finding functions easier when searching by way >> >> of regular expressions. Is that the reason or are there other >> >> justifications? > >> > That's the reason. You can search for the definition, without >> > getting any non-definition use. Also, vi uses a { in column one >> > to recognize the start of a function body, and in practice, >> > there'll be times that you'll have to edit with vi (or ed, which >> > follows the same rules). > >> While I've been there, writing code with ed seems a little too manly ![]() > > You should have used the editor on the original Intel > development systems, then. After that, ed seems like something > for sissies. (The basic philosphy was something like ed, but it > allowed multiple commands on the same line, with constructs for > looping, etc. A typical command line looked a bit like > transmission noise, and an error in a single character could > wreck havoc in your file.) I've used something that sounds very similar for some old embedded coumputers. Actually the word embedded never came up, they were just the command and control computers. Editing wasn't my biggest problem; they had an actual core memory and when a wire broke I had to take it down to a repair facility and solder the broken wire with a microscope. The only good thing was that the facility was just far enough away to make it a two day trip. I usually spent the first day repairing and the second day in the club ![]() > > Seriously, I don't think I've used ed much except for very small > editing jobs in a script. I really think if you had to write a very big program you would save time writing an editor first ![]() >> While I'm primarily an emacs type, I use vim enough to get by >> and others sometimes but I'm not a vim guru. Thinking >> about it, I don't actually remember ever using an actual vi. > > I still use it fairly often. Or production machines have a very > limited environment, and we're not allowed to install just > anything on them. I never turn on compatibility. I might one day just to see if I can still get around without banging into things to badly. I've never found the vim files terribly intuitive, what does the actual vi look like? AFAIK there's no actual open vi, is that correct? >> I read that it's real hard/impossible to create a LALR or even >> yacc compatible grammer for c or c++. > > That's actually true for a lot of languages---even Pascal. The > C/C++ declaration syntax, however, seems to be designed > intentionally to make parsing difficult. I'm pretty comfortable with yacc/bison and flex and I've done many little language things so I have some feeling for working on front ends. However the urge to simply write a c or c++ front end never really bubbled up to the top of my todo list. >> I've never sat down to try but my understanding is there are >> dark corners that cause problems. Is It possible to write a >> yacc grammer that simply recognizes function and class >> definitions? > > If you're handling pre-processed input (or don't mind screwing > up if someone was stupid enough to use the preprocessor in a way > that messed with this), you can come pretty close with just > regular expressions and a state machine. If you're interested, > you might look at the code for my kloc program > (http://kanze.james.neuf.fr/code-en.html, then look for kloc in > the Exec directory). It collects a number of statistics (more > or less accurately), such as the number of functions and the > number of class definitions (those should be very accurate). > It uses only lex and a very simple state machine; I won't say > that it can't be fooled, but it does seem to work most of the > time. (I think. It's really very old code, and I've not really > verified it with templates. I did expand it to handle > namespaces, but I wouldn't be surprised if it didn't get > confused by template definitions which contain parentheses.) Thanks, I'll take a look. I've always found another solution every time I came upon the need but one of these days I really do need to sit down and take a look at this problem; if just for the learning. Last time I needed something I hacked together a script to read a tags file. Seems like the problem comes up often enough for me to add something a little better to my toolbox. Time always seems to work against me when the problem is actually staring at me. >> I know there are programs that detect functions but I believe >> they all do some clever pattern matching; I'm not aware of any >> that try actually parsing. > > Any opening brace at namespace scope is either a class or a > function definition. Knowing that you're at namespace scope > > The syntax for opening a namespace scope > is pretty simple, so you should be able to track those > (supposing no messing around with the preprocessor, of course) > and `extern "C"' blocks. After that, any opening brace at > namespace scope is the start of either a function, a class or an > enum definition. Sounds like a good start for my next rainy day project. Thanks. |
|
|
|
#14 |
|
Messages: n/a
Hébergeur: |
On Apr 10, 5:19 am, stan <smo...@exis.net> wrote:
> James Kanze wrote: [...] > > Seriously, I don't think I've used ed much except for very small > > editing jobs in a script. > I really think if you had to write a very big program you would save > time writing an editor first ![]() On the first Unix system I worked on, they had just finished modifying the OS and the compiler, in order to be able to handle programs as big as vi. Just to not have to use ed. The early Intel editor I used ran on an 8 bit machine with 64 KB, using a teletype as the console. In such an environment, it's hard to do better than ed. (FWIW: vi was the first full screen editor I ever used. Before that, they were all command line editors, like ed.) [...] > I've never found the vim files terribly intuitive, what > does the actual vi look like? What ? There is no on line . > AFAIK there's no actual open vi, is that correct? I think there was, at one time. But why bother? If you're going to compile and install your own, you might as well make it vim (or emacs). (Our production machines are Sun Sparcs, running Solaris, and the only installed editors are those that are bundled with Solaris. Which means the pure Berkley vi, just as Bill Joy wrote it, when he was still a grad student, and hadn't ed found Sun.) > >> I read that it's real hard/impossible to create a LALR or even > >> yacc compatible grammer for c or c++. > > That's actually true for a lot of languages---even Pascal. The > > C/C++ declaration syntax, however, seems to be designed > > intentionally to make parsing difficult. > I'm pretty comfortable with yacc/bison and flex and I've done > many little language things so I have some feeling for working > on front ends. However the urge to simply write a c or c++ > front end never really bubbled up to the top of my todo list. A C front end wouldn't be too difficult, despite the ambiguities in the declaration syntax. C++ probably requires backtracking. Still, I don't think it would be that difficult to get to the stage of building a parse tree. The real fun would start when you start to annotate it. Then comes name look up, function overload resolution, and templates. -- James Kanze (GABI Software) email:james.kanze@gmail.com Conseils en informatique orientée objet/ Beratung in objektorientierter Datenverarbeitung 9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34 |
|
![]() |
| Outils de la discussion | |
|
|