C Formatting Style - Code Appearance - Page 1
Forum section: electronics / general

author: lewis
author_rank: Frequent Contributor
timestamp: May 17, 2014, 11:05:33 pm
content: I always code C like this, it works better formebecause I can see more code without scrolling, and it's the most intuitive to my eyes:Code:void main() {const char array[] = { 0x21,0x22,0x4C,0xB8,0x81,0x88,0xA6 }; //some important arrayunsigned char char_temp, i;if(program_state == AWAIT_FLAG) { //comments go way over here.char_temp = 0; //and here...while(char_temp<sizeof(some_string)) { //...and here...if(UART_Data_Ready()){if(UART_read_byte() == array) char_temp++; //Darmok and Jalad at Tenagraelse char_temp = 0; //Shaka, when the walls fell} //see, comments all in a...} //...nice neat lineE2_prepare_write();if(something) do_something(); //surrender is irreleventeedata_counter = 0; //resistance is futileprogram_state = IN_PROGRESS;} //some rodent I killed}But everyone else in the entire world seems to code like this:Code:void main(){//this array is something important//so I better comment it//on as many lines//as//possibleconst char array[] ={0x21,0x22,0x4C,0xB8,0x81,0x88,0xA6};unsigned char char_temp, i;if(program_state == AWAIT_FLAG){//comments go here and if we need//to span multiple lines then we//just do matter how much space it takeschar_temp = 0;while(char_temp < sizeof(some_string)){if(UART_Data_Ready()){//more comments for this section which does//stuff to something....if(UART_read_byte() == array)char_temp++;else char_temp = 0;}}E2_prepare_write();//inertial dampeners are offlineif(something)do_something();//your biological and technological distinctiveness//will be added to our owneedata_counter = 0;program_state = IN_PROGRESS;}}(Ignore the content, this is just an example). Both methods obviously will compile the same. I find the former the most readable, but I'm outvoted by everybody else!Is my preference lacking in some way?

author: IanB
author_rank: Super Contributor
timestamp: May 17, 2014, 11:10:13 pm
content: Your first example is "C style", your second example is "C++ style".These days C is rarely used, so "C style" is rarely seen. But if you are programming in C, feel free to use the first style.

author: nowlan
author_rank: Frequent Contributor
timestamp: May 17, 2014, 11:24:59 pm
content: To be honest, I consider /* comment */ to be C style, and // to be C++. Maybe I am wrong?How wide is your screen, that you are able to indent comments so far across?I learned to comment every line in assembly, so that was necessary.If I am commenting a block of code I will put the // comment before it.There was a teacher at school, who would get people to limit themselves to a screenful of code at a time.You could condense that while loop into a function to simply the code visually.Although I used only ever do that if code was needed twice.That multi line array declaration in the 2nd example is silly, unless you needed to comment what each value was.

author: IanB
author_rank: Super Contributor
timestamp: May 17, 2014, 11:33:02 pm
content: Quote from: nowlan on May 17, 2014, 11:24:59 pmNo, you are right. I wasn't looking at the comments at all, I was looking at the braces.Code:/* C style */if (x) {/* do something */} else {/* do something else */}// C++ styleif (x){// do something}else{// do something else}

author: tom66
author_rank: Super Contributor
timestamp: May 17, 2014, 11:34:24 pm
content: I prefer C style but for me functions always have braces on new lines. Also, I contract a block if it has one line but only if it has no continuations as such (for example any else-if which takes more than one line means the if must be in braces, even it isn't strictly necessary.) No extraneous spaces or paranthesis around conditionals. And testing for boolean 1 is implied (no == true or == 1.) I'm not sure if it has a name but I've seen it used before.e.g.Code:int foo(int bar, int baz){if(bar == 2) {return baz + bar;} else if(baz < 7) {while(bar > 10)bar -= bar * baz;return baz - bar;}}

author: dannyf
author_rank: Super Contributor
timestamp: May 17, 2014, 11:38:00 pm
content: QuoteNo. Yours is often referenced as Java / K&R.Download a copy of Astyle and it will do various formatting for you.

author: IanB
author_rank: Super Contributor
timestamp: May 17, 2014, 11:39:14 pm
content: Code:while(bar > 10)bar -= bar * baz;is technically C style, but it is contentious. If it accidentally gets reformatted like this:Code:while(bar > 10)bar -= bar * baz;then it can be easy for the casual reader to miss the conditional structure. If you do it this way,Code:while(bar > 10) bar -= bar * baz;then it becomes harder for such mis-formatting to occur.Many style guidelines insist on the {} even for single line cases to ensure the scope of a conditional is always clear.

author: FrankenPC
author_rank: Unknown
timestamp: May 18, 2014, 12:17:21 am
content: A lot of people use C style for JavaScript programming. So, yeah, you're using a well established code pattern. Nothing wrong with it. I don't know anyone who would balk at either format.The trick is to keep it consistent. IMO naming conventions are far more important than layout.

author: Rigby
author_rank: Super Contributor
timestamp: May 18, 2014, 12:26:06 am
content: Are we talking about braces or comments?

author: lewis
author_rank: Frequent Contributor
timestamp: May 18, 2014, 12:28:52 am
content: Thanks guys for your replies. Interesting about the different styles, my copy of K&R shows the curly brackets in the style of my second example.If I'm only putting one command after a conditional operator, I'll put it on the same line without braces. But I won't for 'for' or 'while'. If I'm putting something on a new line, I'll always use braces even if not necessary:Code:while(1) {if(lewis==AMAZING) flash_lights(); //one command after conditional operator?else if(lewis==TERRIBLE) sound_horn(); //...put it on the same line, no braceselse { //more than one command?...open_trapdoor(); //...then on the next line they gokill_indecisive_person();}//except sometimes if i'd like things to line up for...//...some reason. (looks weird but easy to change)// 01234567 89ABCDEFif (lewis==0x01) { PORTA = 0b11011110; PORTB = 0b11010010; }else if(lewis==0xB6) { PORTA = 0b10101010; PORTB = 0b01010011; }else { PORTA = 0b11011100; PORTB = 0b01101011; }for(i=0; i<255; i++) { //I always put contents on...beep(i*16); //...new line in a loop...} //...and use braces even if not strictly necessarywhile(we_wait_for_something) { //same herecheck_some_input();}while(1) {} //unless it's an empty loop}I didn't realise the /* */ comments were C-style and // were C++, I always use them interchangeably. // for singe line comments, and /* */ for commenting out blocks.

author: lewis
author_rank: Frequent Contributor
timestamp: May 18, 2014, 12:32:37 am
content: Quote from: Rigby on May 18, 2014, 12:26:06 amMy OP was referring mainly to braces, tabs and single-command newlines; I didn't realise // was stylistically applicable to one language and /* */ to another

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 12:33:39 am
content: I put open-curlies on the same line as the 'if' or 'while' or other similar block; the only exception is when a function or main() is defined and then I put the open curlie on its own line, as is typical for older K&R.for indenting, I use emacs c-mode and whatever it does, I use and like.one thing that is a bit different about my coding style is that I use a lot of vertical white space. after each function ends, I hit return 4 times (usually) to visually set off that function from the next one. I also do that kind of thing inside routines if and when it makes sense (if it makes things clearer).

author: nowlan
author_rank: Frequent Contributor
timestamp: May 18, 2014, 12:35:38 am
content: I learned something weird about javascript.Code:if(bar == 2) {return baz + bar;To make it easy for beginners, the compiler/interpreter will put in the semicolons, so you need to keep the open brace after then conditional. Otherwise you get this...Code:if(bar == 2) ;; <--- do nothing.{return baz + bar;

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 12:37:09 am
content: Quote from: lewis on May 18, 2014, 12:32:37 amhistorically the /* version was born with C (actually algol, I think) and the // version came with the c++ changes.now, gcc (for example) accepts // even if you are running only the c compiler.but if somepone said 'c style comments' it would be the star version and 'c++ style comments' are //

author: IanB
author_rank: Super Contributor
timestamp: May 18, 2014, 01:15:52 am
content: Quote from: lewis on May 18, 2014, 12:28:52 amThat's curious. This is what I know as "K&R style":

author: jolshefsky
author_rank: Regular Contributor
timestamp: May 18, 2014, 01:17:51 am
content: It typically use a Tektronix 4014 terminal to code. Due to bandwidth limitations, I often code so every set of 35 lines is indented one space more than the maximum of the previous lines. Thus it renders code in columns on the screen, frequently doubling or tripling the number of lines I can display before I need to execute a clear screen command. I tweaked vi to use base 6, so each column is exactly h100 from the previous: the first column is h00-h55, column two is h100-h155, etc.Your code example I would write like this:Code:voidmain(){constchararray[]={0x21,0x22,0x4C,0xB8,0x81,0x88,0xA6};unsignedcharchar_temp,i;if(program_state==AWAIT_FLAG){char_temp=0;while(char_temp<sizeof(some_string)){if(UART_Data_Ready()){if(UART_read_byte()==array)char_temp++;elsechar_temp=0;}}E2_prepare_write();if(something)do_something();eedata_counter=0;program_state=IN_PROGRESS;}}So it would render as:Code:void char_temp=main() 0;{ }const }char E2_prepare_write();array[] if(something)={0x21, do_something();0x22, eedata_counter0x4C, =0;0xB8, program_state=0x81, IN_PROGRESS;0x88, }0xA6}; }unsignedcharchar_temp,i;if(program_state==AWAIT_FLAG){char_temp=0;while(char_temp<sizeof(some_string)){if(UART_Data_Ready()){if(UART_read_byte()==array)char_temp++;elseObviously I wouldn't waste space on commentsinthe code, and would abbreviate the variable names to single letters and document their functionality elsewhere.

author: nctnico
author_rank: Super Contributor
timestamp: May 18, 2014, 01:19:16 am
content: Quote from: nowlan on May 17, 2014, 11:24:59 pmIMHO the best thing to use is // for single line and short comments. That way it is easy to put a whole block of code between /* */ to disable it temporarily or keep the old version for future reference.

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 01:32:04 am
content: I would not recommend using comments to 'comment out' code in C.its better (due to nesting-safety) to use:#if 0...#endifor maybe#ifdef NOT...#endif

author: Rigby
author_rank: Super Contributor
timestamp: May 18, 2014, 02:09:39 am
content: don't keep the old version commented in any way for future reference. put a link to the old version (which is of course stored in a code repository, right...?) in the code instead. Or, just understand that your developers know how to use source control and know where to look for old versions, because they've probably been doing this a while.linux-works and I have had it out before over the ifdef commenting biz. I still don't get it, and I disagree with it, because if you're doing that, I personally believe, and no one else may agree with me, I think I have pretty good reason to believe that your code is structured incorrectly if debugging requires or is assisted by huge blocks of code being removed. My sentiment there may not make sense on some platforms, maybe your production hardware does not allow debugging or simulation or whatever; fine. But if there is a debugger available to you, if there are any decent tools available to you --AT ALL-- then using large blocks of commented code to test things just doesn't make sense.

author: aroby
author_rank: Regular Contributor
timestamp: May 18, 2014, 02:27:31 am
content: I always use braces on a separate line - makes it easier to see where the functions start and end, although that is probably just a habit from the days when we had to print out the code to desk check it.Glad to see you use comments. I got into the habit years ago of commenting code extensively - especially useful at 2 am in the morning when production is down! I hate the way people today don't comment code. There's a project I'm trying to participate in on github written in node.js which is impenetrable - not a single comment anywhere. Drives me nuts.Anthony

author: Hypernova
author_rank: Unknown
timestamp: May 18, 2014, 02:30:32 am
content: // for short one line comments and /**/ for multi line comments that precede a large function block.For arrays often I have to comment what individual item is so I format the auto formatter to multi line.Compensating for screen size is counter productive IMO if it impacts the reader's ability to see the structure of the code at a glance. I code on a 1920*1200 24", and Dell just released a pretty decently priced 28" 4K display which I've been itching to get.

author: Ed.Kloonk
author_rank: Super Contributor
timestamp: May 18, 2014, 03:58:58 am
content: Quote from: IanB on May 17, 2014, 11:10:13 pmFirst example reminds me of ASMQuote

author: ejeffrey
author_rank: Super Contributor
timestamp: May 18, 2014, 05:56:52 am
content: Quote from: linux-works on May 18, 2014, 01:32:04 amMeh. Any editor with syntax highlighting will show you the problem immediately, and even if you miss that it is going to generate a compiler error almost certainly as */ is not otherwise a valid token -- you need a pretty bizarre set of circumstances to get a nested comment bug to compile. Yeah. if you really need to disable something with /* */ inline you should use #if 0, but that should be a relatively rare occurrence. I wouldn't suggest using #if as a general purpose comment.Assuming you are using VCS, the only legitimate case I can see for having commented blocks of code is if you are using it for documentation. For instance, if you have two versions of a routine -- one that is easy to read and one that is heavily optimized or uses inline assembly. In that case, the correct answer is not #if 0, but to use #if OPTIMIZED / #else / #endif so that you can use a compiler directive to switch to the reference version.

author: VK3DRB
author_rank: Super Contributor
timestamp: May 18, 2014, 06:42:19 am
content: Quote from: IanB on May 17, 2014, 11:10:13 pmWhat!!??? These days C is rarely used?I strongly disagree.You must be a Windoze programmer. Most programmers of PICs an Atmels use C as language of choice, primarily due to its power, efficient compilers and object code.Most Windoze programmers do not make good embedded C programmers, because they don't have the paradigm to work within limited memory, slower clocks, instruction cycle timing and other resources. Most don't know how a microcontroller works, and fumble around using interrupts or task management efficiently. I have seen C++ and C# Windoze programmers make a right mess of embedded programming and have had to have their stuff rewritten.

author: nctnico
author_rank: Super Contributor
timestamp: May 18, 2014, 07:34:33 am
content: Quote from: Rigby on May 18, 2014, 02:09:39 amI often comment out large chunks of code I don't want to throw out immediately or want to re-enable later on for testing. I do a lot of work on other people's code and in many cases that means disabling some parts to see what it actually does. Putting it between /* */ is the easiest way because you can do this://*some code//*/Removing the first / enables 'some code' and adding one / disables the block of code.

author: VK3DRB
author_rank: Super Contributor
timestamp: May 18, 2014, 07:42:58 am
content: I prefer offset braces (you get more lines on a monitor), but am happy to use the Windows in-line braces if it is the adopted coding standard.No self respecting company would write code without using C CODING STANDARDS. Coding standards are vital. That means everyone, now and in the future adopts the same coding style. I knew a bloke who would vary his crappy coding style as he was programming.Consistency and the ability to communicate the code to the next poor bunny just as important as the compiled code. Inheriting a mess from an idiot is soul destroying.In general electronics engineers do not make great programmers, basically because many have never been taught to write their code clearly, logically, and well commented. I am an EE, but I am strict when it comes to writing clear, consistent code. I once fired a bloke partly because his code was. I do know EE's who can write professional looking code, but they are not that common.Some requirements to writing good C code include the following:1. Use C coding standards.2. Know how to spell. If you cannot spell, get out of the kitchen.3. Use unambiguous function, variable and constant names4. Don't abbreviate anything if it is going to confuse people. Don't be lazy.5. Use CamelCase for function names and variables. AndNeverUseUpperCaseForAcronymsLikeIbm, thus clearly delineating acronyms from words.6. Do not use underscores in function names and variables. Use underscores for constants. eg: AMBIENT_TEMPERATURE 257. Make your .c and .h file names unambiguous, clear and modular.8. Comment WHY you have done something, not WHAT.9. Line up comments within in a block of code.10. Have code reviews.11. It is better to over comment than under comment.... the list goes on.I do use the // for comments pertaining to one line:setpointTemperature = AMBIENT_TEMPERATURE // Reset the temperature because the cooling has completedAnd use /*...*/ for blocks of code:/* Read the integrated PWM voltage */{yada...{You can join single line comments to make a sentence using three dots:temperature = ReadTemperature();inputVoltage = DoAdc();if (temperature > 32) || (inputVoltage > 5.0) // If we have detected a fault...{ShutOffSystem(); // ...shut down the machine}Notice also, that for variables I use a lower case character for the first character in the first word, but all words in function names all start with an upper case character. It seems to make it more readable. Another idea I adopted was to use the verb in the function name first. This helps reduce ambiguity. eg:SetTemperature();Well all make mistakes of course, and if you are like me typographic errors do occur occasionally. One reason it is well worth getting a peer to review your work.

author: dannyf
author_rank: Super Contributor
timestamp: May 18, 2014, 11:16:56 am
content: QuoteI do the exact opposite: Temperature_Set(), Temperature_Get(), ...The advantage there is so all temperature related functions start with Temperature_....

author: con-f-use
author_rank: Unknown
timestamp: May 18, 2014, 01:31:15 pm
content: I'm in scientific computing. There C or even Fortran is the language of choice, because a lot of programs are ancient and have to be backward compatible with older instrumentation and code modules. In our HPC programs (Millenium Simulation/Illustris project etc.) everything is written in C because of performance (heavy use of hardware optimization, OpenCL, MPI and OpenMP).As to the // vs. /* comments: The former were introduced into C with the advent of the C99 standard. Original 1st edition K&R style was different from everything here and looked like this:Code:int power(x,n)int x, n; /* note how the data types for parameters are declared */{int p;for(p=1; n>0; --n)p = p * x;return(p);}

author: John Coloccia
author_rank: Super Contributor
timestamp: May 18, 2014, 02:09:10 pm
content: There weren't a lot of things I put my foot down with, but lining up curlies was one of those things. Not up for debate, non-negotiable. I got sick and tired of helping people track down missing curlies when they got "Unexpected End Of File" compiler errors, and I seriously got sick and tired of tracking down logic errors because people had trouble figuring out just exactly which control statement they were in. It also just looks stupid because it doesn't even match the way functions are typically braced. Why the distinction? No reason, that's why. This style is a hold over from terminal days when you really did want to save a few lines here and there. It's completely antiquated and should be done away with, IMHO.I've yet to meet the new programmer that naturally gravitates towards K&R. In my experience, they universally prefer curlies on a separate line, and for curlies to line up. A lot of older programmers prefer K&R style because that's what they're used to, but a lot of them also prefer VI, so make of that what you will.:wq

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 02:43:57 pm
content: even if you don't use emacs, its a great tool to do a quick indent and a syntax color display.you could select a block of text and run the c-indent function and it will show you if one curlie goes too far to the left.I tend to leave my emacs windows open for months at a time and I've become very used to c-mode and c++-mode. the color, the auto-indent, the multi windowing - it makes life easier.I suppose IDE's are the more expanded version of that, and some people like the dedicated IDEs.if I have to understand some new code, I'll often pull it into emacs and run indent on it just to see the true nesting of the code.

author: nctnico
author_rank: Super Contributor
timestamp: May 18, 2014, 03:30:55 pm
content: Quote from: John Coloccia on May 18, 2014, 02:09:10 pmI agree. I always align the curlies. When people complain they don't want to use that style in their project I tell them they can go Format themselvesLot's of tools to do that. When working on projects from others I usually reformat the code according to the style I prefer.

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 04:13:51 pm
content: it might be a silly thought to some, but I've always wanted a tool that would be able to check a file out, format it to your liking, let you do edits, but when you check it in, it saves it in the group-standard format along with some meta data about how you like your file presented. if someone else checks it out, they get the same but that their style is used in their edit session and when they check it in, its put back into group-standard format, etc.it does not sound like an easy task; lots of areas where things could break, in this scheme. but I sure would love to have something like this. a version control system might be a starting point, with significant changes.we have so many version control systems but I've never heard of anything like what I'm describing. we need something like this. I bet people would enjoy code devel more if they weren't forced to edit and live in someone else's style, yet when they checked code in it was fully conformant. win/win.

author: con-f-use
author_rank: Unknown
timestamp: May 18, 2014, 04:59:58 pm
content: People who complain about code formatting, don't realize there are programs that convert it to your favourite style and back. It's really a non-issue as most personal preferences. How to comment your code and name your identifiers should be the emphasis.

author: lewis
author_rank: Frequent Contributor
timestamp: May 18, 2014, 05:06:26 pm
content: Quote from: nowlan on May 17, 2014, 11:24:59 pmTwo 2560x1440 side by side in my office. When I'm on my laptop at home there's lots of horizontal scrolling! But the monitor is still wider than it is high, so I like to use as much horizontal space as possible.Quote from: IanB on May 18, 2014, 01:15:52 amYou're absolutely right, I just skimmed through my K&R before posting and saw the curly brackets on new lines under the function names. Seems they use a mixture of both stylesQuote from: jolshefsky on May 18, 2014, 01:17:51 amI find that really really hard to read! But if it works for you, why not?Quote from: linux-works on May 18, 2014, 01:32:04 amI don't do this, I always use comments. Is there a good reason to do it this way? My compiler requires that valid code be present within all pre-processor directives, so you can't use this to 'comment' out variable names, functions and other stuff that you might have modified, deleted or commented out elsewhere.It's amazing how may different preferences and methods there are.

author: zapta
author_rank: Super Contributor
timestamp: May 18, 2014, 05:15:55 pm
content: Quote from: con-f-use on May 18, 2014, 04:59:58 pmTbbq cbvag. Fb ab ceboyrz cbfgvat urer va ebg13 fvapr gurer ner cebtenzf gb pbairegf onpx naq sbegu ;-)

author: John Coloccia
author_rank: Super Contributor
timestamp: May 18, 2014, 05:19:11 pm
content: Quote from: lewis on May 18, 2014, 05:06:26 pmHow can it do that? A main use of conditional compilation is to switch back and forth between libraries and features that may or may not exist on various platforms. This would completely break if valid code was required in preprocessor directives. I'm not even sure that would conform to the C standard.Anyhow, a good reason to use comments instead is so that the syntax highlighting in your editor can clearly show what's what. I generally always use C++ style comments (//) to do actual comments, and C style comments to comment out chunks of code. Since C99, it's acceptable in both C and C++, though C compilers have been accepting C++ style comments for much longer than that.

author: lewis
author_rank: Frequent Contributor
timestamp: May 18, 2014, 05:37:07 pm
content: Quote from: John Coloccia on May 18, 2014, 05:19:11 pmI've just tried it, and of course you're right! I was getting confused with valid code in unused functions.

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 05:49:21 pm
content: Quote from: lewis on May 18, 2014, 05:06:26 pmits how I grew up, and it was the only portable common safe way to comment out blocks of code, even nesting it deep and deeper, since if-def nesting works. comment nesting was not supported (and not great practice, either) and so we avoided it.at every place that I worked since the mid 80's, this was common practice. using comment chars to temp disable a block was bad. using ifdefs was good.was it ifdef 'abuse'? yes. but so what?its just common practice, its part of the lore and style of C and it will be there if you like it or not. it may not be the only way, not, with modern compilers, but historically it was the best way and it still does work, today, with no problem. I like that the old way worked then and still works today. and so, I continue to use it when I need to comment out blocks for short term testing.

author: jancumps
author_rank: Unknown
timestamp: May 18, 2014, 06:09:16 pm
content: I'm into software later than you; I started in the mid 90's. I haven't encounter the #ifdef construct as a commenting mechanism. I've seen it used for conditional compilation, debug specific behaviour and include file management.

author: John Coloccia
author_rank: Super Contributor
timestamp: May 18, 2014, 06:25:50 pm
content: Quote from: jancumps on May 18, 2014, 06:09:16 pmIt's a hold over from C when all you had was /* */ style comments and commenting out full sections was very difficult...and uncommenting all of them was even more difficult and error prone. Easy to miss one. These days, it's pretty standard to use C++ comments for most comments, and C style comments to disable code for debugging and emergency builds. Very very standard practice.

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 06:29:52 pm
content: my first days with C was with vax/vms and ultrix. this was before ANSI C and you had to do stuff like:int abc(x,y)char x;int y;{more_stuff(x,y);return 1;}you could not put the char and int stuff on the same line, back then. they added that with ANSI but old K/R C made you put those formal parms to the function on their own. it was an ugly style and everyone was glad to see the new form:int abc(char x, int y){...}and so, its a habit from the early days. the ifdef way of hiding code just was a nuts-and-bolts way of trying out things, or dividing and conquering some section, under your control. also, when doing a compile took a long time, you would also ifdef-out some sections and stub it with simulated values just to make the build and debug process go fasteryou would NEVER do that today since cpu is infinite and free and fastI still do the ifdef thing and I use it a lot for a lot of things. if you see someone do that, he's probably a greyhair (for good or for bad).

author: zapta
author_rank: Super Contributor
timestamp: May 18, 2014, 06:36:11 pm
content: Quote from: jancumps on May 18, 2014, 06:09:16 pmWith modern IDE's it's very easy to comment out a block of code using // in each line. It has the same affect and it's more visible that this code section is out.New IDE's and C++ reduced the need to use #preprocessor directives and I try to avoid them as much as possible (using inline function, typed 'const' constants, etc).

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 06:47:28 pm
content: in that other thread, from a few months ago, it was discovered that even vi would understand the ifdef or whole block comment-out thing and whatever you did, it 'knew' and would colorize things nicely, showing the block is not in the current edit/build. I was surprised that it could read inside and know this, but found it pretty cool that it could.if you're learning now and your method works for you, that's great. but you will see code in the older style, if its been around 20 or more years.

author: con-f-use
author_rank: Unknown
timestamp: May 18, 2014, 08:18:46 pm
content: Quote from: zapta on May 18, 2014, 05:15:55 pmPardon me?

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 08:27:05 pm
content: you've just been rot13-rolled.LOL

author: zapta
author_rank: Super Contributor
timestamp: May 18, 2014, 08:52:27 pm
content: Quote from: linux-works on May 18, 2014, 06:47:28 pmYes, that's true, when syntax is enabled. Not sure about other tools such as diff (probably will not show the commented out section, just the top and bottom lines).I started with K&R and then came ANSI (great improvement) and then C++ (even better). Still using #preprocessor for thing that the language does not support (e.g. .h include guard) but try to avoid it as the plague.For example, I would prefer const uint16 myConst = 7; over #define x 7. Modern compiler are smart enough to optimize at compile time whatever they can so I don't pay much attention to it.

author: grumpydoc
author_rank: Super Contributor
timestamp: May 18, 2014, 09:51:20 pm
content: QuotePlayed around with this as an idea in the early 1990's using "indent" - kind of worked but not really well enough to be anything other than an interesting idea.To be honest when you've coded enough you will realise that the particular style does not matter a great deal but it is important that a given project/company/whatever has a style and it is consistently applied.Until you buy a third-party library that has source and it isn't the house style......

author: linux-works
author_rank: Super Contributor
timestamp: May 18, 2014, 09:54:07 pm
content: for me, I feel more comfortable with my own (ie, emacs stock indent) style and if I can reformat to that, I can speed thru it much easier than if its left in flavor-of-the-day format for this or that company or group. companies and groups will change but I've kept my style for decades, now.so, there's real value in being able to view and edit in your style but then check back in to standard format and keeping enough diffs in meta data so that next checkout you do, it looks like its always been in your format.that would be magic. I'd love thatbut I have not heard of anything that is reliable and usable along these lines. you are expected to conform to THEIR coding style and people just give up assuming that's how it has to be. I just wonder if there isn't a better way...

author: zapta
author_rank: Super Contributor
timestamp: May 19, 2014, 06:12:18 am
content: Quote from: linux-works on May 18, 2014, 09:54:07 pmBetter way? Maybe the golang approach. The language comes with an official code formatter that resolves all the ambiguities. One practice I saw is to run it automatically from the checkin hooks so nobody needs to bother with it. Java also has an official style but it's often no obeyed (e.g. curly braces on a separate line, indent of 2 instead of 4, etc).BTW, the picture collection in your signature is very interesting.

author: con-f-use
author_rank: Unknown
timestamp: May 19, 2014, 11:36:27 am
content: Quote from: linux-works on May 18, 2014, 08:27:05 pmI suspected it was some sort of Caesar cipher, but didn't want to spend time on trying all shifts. Had it been C-Code, I'd 1.) immediately seen it was actually language and 2.) not been that lazy if it was work related. Brackets on same line vs. on a line by themselves really just one parameter. Bottom line: It's kind of a mute point. Of course it adds an extra layer of complexity, but if there are competing, widely used standards, you don't get around it. It's not like rot13 is used in 30% of printed books.

author: amyk
author_rank: Super Contributor
timestamp: May 19, 2014, 01:59:45 pm
content: There are tons of styles, here's some of the more common ones:http://en.wikipedia.org/wiki/Indent_styleMine is a little more compact than average; I use just enough whitespace to show the structure, and blank lines only to separate functions, since I use blank lines within functions as hints that it's currently incomplete and where I should continue working when I come back to it later.Code:int fu(int x, int y) {if(foo())bar();else {*baz() = 5;x += y - m();}return x > y;}

author: aroby
author_rank: Regular Contributor
timestamp: May 19, 2014, 02:03:19 pm
content: Quote from: VK3DRB on May 18, 2014, 07:42:58 amAmen

author: Galaxyrise
author_rank: Frequent Contributor
timestamp: May 19, 2014, 03:43:36 pm
content: Quote from: lewis on May 17, 2014, 11:05:33 pmThe arguments I've run into for "brace on the next line" are:It's universally consistent for all braces in the program, from functions to random variable scopingIt's easy to visually match the braces verticallyIt better handles multi-line block starts (such as a multi-line if condition)Both styles are still pretty popular as far as I know... I seem to recall someone analyzing github commits or something. Brace style can become the subject of a "religious war".As for skipping the braces for one-liners, the best argument I've seen against that would be the Apple goto bug. That looked for all the world like a bad source merge, and it probably would have been either harmless or a compile failure if they'd used the "extra" braces. Other arguments I've encountered (which haven't convinced me to always use braces, hehe):It's easy to mess up nested if/else matching without the bracesIt's a pain to add the braces later when you need to make the logic more complicatedIt's easier to distinguish the body from the conditionAs for your commenting style: Generally, when I want to comment something, it's because I need to describe something pretty tricky... a race condition that I'm avoiding, a mathematical derivation, some obscure chain of events that makes this case actually possible... and I'm not comfortable annotating it in your style. Syntax highlighting has removed the need to format the code to make the comments easy to find, so I use comments to break up the code into logical blocks.

author: ejeffrey
author_rank: Super Contributor
timestamp: May 19, 2014, 04:30:14 pm
content: Quote from: Galaxyrise on May 19, 2014, 03:43:36 pmThe merge conflict this is a real issue, but this one just pisses me off now. Our IDEs/editors shouldn't let this happen. I am not a big fan of the python approach of omitting braces entirely, but I think they are spot on with the idea that if the indentation is wrong the code is wrong. If I am editing a block of C code and there is an else block whose indentation doesn't match the language syntax, it should be highlighted blinking hot pink and dayglo green, and damn well make me fix it. Same with any other indentation errors. I wouldn't be opposed to a compiler flag that made incorrect indentation an error.

author: zapta
author_rank: Super Contributor
timestamp: May 19, 2014, 04:37:17 pm
content: Quote from: ejeffrey on May 19, 2014, 04:30:14 pmThe braces allow the IDE to detect indention conflict while the python approach does not.in Cif (x) {a;b; // Tools can flag this indentation conflict.}and in pythonif x:ab // valid but different semantic. No way to raise a warning.

author: FrankenPC
author_rank: Unknown
timestamp: May 19, 2014, 06:04:15 pm
content: One commentator said "it's better to over comment than under"I disagree. I've seen code with pages of comments that was totally un-readable.The problem with comments is they aren't formatted for the human eye. They are usually a monchrome color and poorly formatted. It would be nice to see some kind of real time text formatting inside the comment fields.

author: Rigby
author_rank: Super Contributor
timestamp: May 19, 2014, 06:28:11 pm
content: Quote from: FrankenPC on May 19, 2014, 06:04:15 pmYou've been reading spectacularly poor comments, I would think. Can you explain how they are unreadable? Unless they're formatted terribly or are in another language, I don't understand how comments can be bad, unless the person that wrote them has his/her own way of saying things. Even then, the problem is the commenter, not the comments.The best code I've read has very well chosen variable names. This, and an avoidance of premature optimization make for uncommented code that can be very, very clear to a future reader, even without any comments or other documentation.

author: jancumps
author_rank: Unknown
timestamp: May 19, 2014, 06:34:36 pm
content: The 'too much' and 'too few' qualifier already indicate that something is wrong. At that point the issue isn't caused by the mechanism, but by not using it properly.

author: con-f-use
author_rank: Unknown
timestamp: May 19, 2014, 06:45:30 pm
content: Ah coding style is such a rewarding topic. But yes, excessive commenting is annoying. People should write their code in a way that doesn't need commenting at all. If for no other reason, than because commenting is double work. When you change something, you need to change the comment as well. I use them for basic orientation in my code, and when I'm using an algorithm that is not self evident.

author: Rigby
author_rank: Super Contributor
timestamp: May 20, 2014, 03:04:22 am
content: Quote from: con-f-use on May 19, 2014, 06:45:30 pmSo fold it out of the way?It is much harder to write code that needs no doc than people sometimes think. Comments are just common courtesy to other devs, or to yourself in the future. Non-obvious logic requires comment.

author: con-f-use
author_rank: Unknown
timestamp: May 20, 2014, 08:05:55 am
content: Yes, but you missed my point. Before writing a comment, make sure it is 1) needed and 2) you can't rewrite the code so that the comment isn't needed.

author: IanJ
author_rank: Unknown
timestamp: May 20, 2014, 10:54:22 am
content: Hi all,I do a lot of Arduino programming at home and use Notepad++ as my choice editor. With that I get all the colours and ability to align curlies etc fairly easily. But as I'm not a programmer as such. My biggest prog being say 500 lines of code spread across 10 files (not including libraries). So, I've kinded invented my own way of doing things which from what Notepad++ can do for me and from what I pick up elsewhere.Works for me.......just don't ask me about "standards". I know I make plenty of mistakes.PS. Black background because it's easier on my eyes.Ian.

author: Rigby
author_rank: Super Contributor
timestamp: May 20, 2014, 01:00:35 pm
content: If you like the black background as I do, then maybe you'll also like the Consolas font, as I do. It's easier on the eyes than Courier New.

author: HP-ILnerd
author_rank: Frequent Contributor
timestamp: May 20, 2014, 05:30:05 pm
content: I like coding green on black with yellow comments.The contrast is pretty much sweet-spot, so you can stare at it for hours.The default studio.net IDE colors look like someone threw up on the screen.I like // comments for commenting code, but /*...*/ for commentingoutcode.Quote from: Rigby on May 20, 2014, 01:00:35 pmThanks for the tip on the Consolas! Itdoeslook nice. I'll have to give that a shot.

author: SirNick
author_rank: Frequent Contributor
timestamp: May 20, 2014, 08:46:06 pm
content: I like a good syntax-highlighting code editor (e.g., Kate, vi, Notepad++ in order of preference) rather than a full IDE. The smarter an IDE gets, the more it tends to get in my way.My own preference is to use // C99 / C++ style comments, unless the comment block is more than say 5 lines long, or I'm temporarily removing a section of code (because I specifically want to avoid its effect, or want to test an alternate algorithm -- not for long-term change control.)I like opening braces on the same line as the function / conditional, although if the block is more than one or two lines long, I leave a blank line after the function / conditional (where the opening brace would otherwise be) for clarity. If I'm writing a conditional that spans lines, I'll often put the brace on a line of its own because it looks cleaner, and the conditional is probably pushing the right margin enough as it is.I believe in white-space. Code that is logically glued together (e.g., a bunch of variable declarations) goes on consecutive lines. Non-trivial statements have a single line between them. Statements that are essentially a new "thread" have two lines between them.I stick to 80 columns because I do sometimes use CLI text editors. Even when I'm editing in a GUI, I like the narrow format so I can split my editor into two columns (.c in one, .h in the other), and will often have a second monitor with another split view for whatever headers are commonly referenced by the code I'm working on.I put single-statement conditionals on one line. If the conditional is long-ish, the statement will be on the next line. If I'm likely to extend it or add debug prints or whatever, it'll have braces, otherwise it probably won't. Yes this can lend itself to compile-able syntax errors. So can writing any code at all ever. That's life.Four spaces to indent. I don't like tabs because they're different everywhere, and at least with spaces, what I write will line up properly regardless how many characters your editor thinks a tab should be. Most editors can intelligently handle tab stops aligned with spaces, and no-one uses Helvetica to write code. Don't like it? OK, here ya go: s/\s{4}/\t/gI comment the thought-process of each block of code because I want the reader (me, usually) to be able to follow what's happening with a single glance. If the comments are clear and concise, they should always be more easily parsed by the human mind than code -- regardless how simple or well-written the code is. (Bad comments and non-native languages notwithstanding.)Rule #1, with no exceptions, is that whatever formatting is there, is there to make the code easier to read and understand. I will break any and every other rule when it serves clarity. There are a plethora of tools to make it look however you want, so if you end up working on my code and don't like my style, by all means -- change it. Whatever helps you write better code, and whatever the compiler understands, is fine by me.Here's an example function from my current project for the curious:Code:// Prepares a new socket for sock_listen() or sock_connect()uint8_t sock_open (ip4_addr src_addr, uint8_t proto) {uint8_t i;uint8_t x;uint8_t sock = 0;uint8_t bind = 0;// Check for an available socket entryfor (i = 0; i < IP_SOCK_MAX; i++) {if (ip4_sockets.status != IP_SOCK_FREE) continue;// Claim this socketsock = i;ip4_sockets.status = IP_SOCK_RSVD;break;}// No free socketsif (i == IP_SOCK_MAX) return IP_SOCK_INVALID;// Check interfaces for a corresponding source addressfor (i = 0; i < IP_IF_MAX; i++) {// Skip unregistered interface entriesif (ip4_bindings.flags == IP_IF_FREE) continue;// Check address entries for a matchfor (x = 0; x < ip4_bindings.addr_count; x++) {if (ip4_bindings.addr != src_addr) continue;bind = i;ip4_sockets.bind = bind;break;} // for addr_count// Bail out if an address was foundif (x == ip4_bindings.addr_count) break;} // for IP_IF_MAX// Search failedif (i == IP_IF_MAX) {// Release socketip4_sockets.status = IP_SOCK_FREE;return IP_SOCK_INVALID;}// Set socket propertiesip4_sockets.proto = proto;ip4_sockets.flags = IP_FLAGS_NONE;return sock;}

author: Rigby
author_rank: Super Contributor
timestamp: May 21, 2014, 02:25:16 am
content: Quote from: SirNick on May 20, 2014, 08:46:06 pmAnd that is how buffer overflows, memory leaks, and unchecked bounds vulnerabilities happen, everybody.You are either using the wrong IDE or you aren't willing to let the IDE assist you. There is no reason, in 2014, that a developer should use a syntax highlighting Notepad.IDEs, once set up, are indispensable to me. When I set up Eclipse for Java or C work, I spend several hours installing plugins and configuring the hell out of just about everything. The result is an IDE that helps me, does everything I want, nothing I don't want, checks for dead code for me, profiles my code for me, reports on unit test coverage for me, and most of all, tells me when I code stupid things that create known vulnerabilities.There IS an IDE out there somewhere that will work for you, rather than against you.

author: HP-ILnerd
author_rank: Frequent Contributor
timestamp: May 21, 2014, 03:10:23 am
content: Quote from: Rigby on May 21, 2014, 02:25:16 amQuite agree. I've been doing this long enough that I remember writing code that compiled cleanly and promptly exploded upon execution. I actually snow-crashed a machine once.Today, nothing dramatic ever seems to happen. Yes, decades of experience make a big difference, but so does an IDE that can keep you from doing something silly, or somethingperfectly legal that is totally not what you meant. Plus, the added debugging tools can help you chase down something subtle. Ever spent 8 hours looking for an intermittent that turnedout to be just one line that only failed under very specific circumstances? I'll take all the help I can get.

author: ejeffrey
author_rank: Super Contributor
timestamp: May 21, 2014, 06:10:01 am
content: Quote from: HP-ILnerd on May 21, 2014, 03:10:23 amThe IDE is almost certainly the least important variable there. Experience as you noted is probably the biggest, but the second biggest is improvements in operating systems, languages, libraries, and coding practices -- learning to provide safer alternatives to dangerous coding practices and create statically safe constructs whenever possible. Better developer tools, including but not limited to IDEs are third place. In any case, most of those tools are available outside an IDE as well, and developers concerned about reliability use memory analysis tools, coverage analysis, unit testing and so forth whether they do so from an IDE or not.

author: Dago
author_rank: Frequent Contributor
timestamp: May 21, 2014, 10:44:32 am
content: Quote from: SirNick on May 20, 2014, 08:46:06 pmI have to agree with SirNick on the IDE/editor thing. I just really hate tools which do stuff without me being clearly in control and know what they are doing. I have to use some IDEs at work and I hate the fact that I have no idea what the build system etc. is doing. If I want to change something I just have to kind of aimlessly wander around menus till you find something related.With gcc toolchain + make it's really clear/obvious what is happening and what is not happening.Every time I try to use and IDE I just get frustrated with not finding what I want and the IDE doing tons of stuff I do not want. Haven't found much features that I'd need or like to have compared to a pimped out vim.

author: dannyf
author_rank: Super Contributor
timestamp: May 21, 2014, 10:50:18 am
content: QuoteThat depends on what you mean by "know". Do you really want to know how iron reserves are discovered? how iron ore is mined? how it is transported, milled and then machined into bolts, beams, struts and door handles before you are willing to drive your car or ride your bike to work?QuoteIt could be an issue of those IDEs or your inability to know how they work. Hardly an issue for IDE.QuoteKnowing too much can be bad and wasteful, depending on your priorities.

author: Dago
author_rank: Frequent Contributor
timestamp: May 21, 2014, 11:01:29 am
content: Quote from: dannyf on May 21, 2014, 10:50:18 amI am a person who likes to know as much as possible because in my opinion it never hurts. I'd make the analogy to a baker. Someone might be only interested in the fact that you have an oven and out comes bread. In case if the bread tastes like crap your only solution is to fiddle around with the oven aimlessly and hope the bread turns good again. I'd like to know how the oven works so that in case of trouble I could make the one and only needed adjustment that would fix the problem.I was at a training course for a commonly used automation system and I'd hate to work with a system like that. Everything was integrated to one IDE, even the trainers had NO idea what was happening and what the system was doing. In case of problems (and there were a lot even in the time span of two training days...) the only solution was to reset the system/bus or power cycle it or reboot the software or your computer.

author: dannyf
author_rank: Super Contributor
timestamp: May 21, 2014, 11:22:54 am
content: QuoteWhat we know is infinitesimal vs. what we don't know: we don't know fully how the ecosystem works, and that didn't prevent us from living; we don't know how our brains work, that didn't prevent us from thinking; ... You will find that we exhaust our knowledge if you take a few steps in any direction.Most people take the practical approach: they make an assessment of how critical the lack of knowledge is for their task at hand, and how much incremental value there is to know more.Every second you spend in learning means a second you didn't spend in doing something else. That can be a huge opportunity cost, depending on who you are and where you are in your life.Yeah, learning can be very expensive.

author: Rigby
author_rank: Super Contributor
timestamp: May 21, 2014, 01:44:17 pm
content: Quote from: Dago on May 21, 2014, 10:44:32 amSo be in control and know what they are doing, then... Are you seriously going to let software control YOU?

author: HP-ILnerd
author_rank: Frequent Contributor
timestamp: May 21, 2014, 02:37:50 pm
content: Quote from: ejeffrey on May 21, 2014, 06:10:01 amFair enough. Your ranking seems quite accurate (for me, anyway). For the vast majority of the time, the IDE is just an "autocomplete" machine for method members (<-useful!!), but for that tiny fraction of a time I have to (for instance) single-step through something, I want the IDE. The one-stop-shopness of an IDE is too convenient to not want. Plus, perhaps more importantly, with all the RAD tools for building the interface built into a modern IDE, the idea of going back to typing in resource file data of where you want your buttons to go is not appealing. Even using a separate tool to paint the interface and have it generate the resource file lacks the interactivity an IDE provides to smooth out developing an interface. I.e., making a small adjustment is perfectly convenient. I like to be able to just drop (say) a button anywhere on the blank interface document, click it--bang! Interface code for that element is built and working, now I only have to worry about what itdoesand where a good spot for it is relative to the other controls.Even when I blackbox my code so the interface is only a shell, which is usually, the IDE is still very useful.If you are only doing microcontroller or other embedded work, the above may well be less relevant.But even with all that, sure: experience is the most important thing. Spaghetti code, for instance, is something caused by the programmer, not the language.

author: SirNick
author_rank: Frequent Contributor
timestamp: May 21, 2014, 07:19:29 pm
content: Quote from: Rigby on May 21, 2014, 02:25:16 amDefinitely not the response I was expecting.Using an IDE prevents buffer overflows? OK...I have some trouble imagining how all that intelligence can be reliable. Someone has to write the unit tests, don't they? How could an IDE write appropriate unit tests for you? So if that part is still manual, it's just an automated build system that runs the tests on your behalf, no? What's the difference between that, and writing my own unit tests (which I do), and requiring them to pass before the Makefile will continue (which I do)? (I'm not challenging anyone here, just curious if / how it's better than what I'm doing now.)I get the utility of an IDE for performance profiling and debugging (when the hardware supports it). I do some Linux dev stuff, for which I use tools like valgrind, and embedded stuff, for which I'm not used to having many options. Although, I do try and write libraries that will build on Linux for testing. I'm even working on some test harnesses to provide simulated interfaces -- not real HW simulation, just whatever is necessary to fake the I/O ops.Interesting comments on this topic. I had always seen an IDE as something that hides the build process, adds include paths from FSM-only-knows where, spares you the indignity of typing "mkdir" for new projects, finishes your (sentient | sentence | sentimental)s for you with the wrong keywords if you should happen to press Enter or Tab at the wrong time, and inserts closing parens and braces where you don't want them. (A "feature" I can't find a way to disable inVisualAtmel Studio...)

author: Rigby
author_rank: Super Contributor
timestamp: May 21, 2014, 08:57:41 pm
content: Quote from: SirNick on May 21, 2014, 07:19:29 pmAnd IDE can very quickly tell you when something like that is wrong in your code. It's true that an IDE isn't completely necessary to run a static analysis tool on your code, and it's true that using an IDE gets you out of that thought spiral that "tools are bad and get in my way."Static analysis tools have found bugs that even the best C/C++ developers have missed, on code they've worked on for years and years. A year or so ago, John Carmack tweeted a bit about static code analysis on his id Software code, and found that there were lots of embarrassing mistakes in his code that he's overlooked for years and years. He is considered one of the very greatest graphics developers of all time and he uses C/C++ exclusively for production work. My point with that is that there is no one on the planet who can't benefit from those tools, and the attitude that tools just get in the way does nothing to help make code better.And then there's the irony that programmers don't like tools... programmers MAKE tools.

author: SirNick
author_rank: Frequent Contributor
timestamp: May 21, 2014, 11:37:59 pm
content: Well I lost a few hours to reading articles on static analysis, so thanks for that.Although I still don't see whether you use and IDE or not as a relevant factor in this equation. For me, analysis would be a conditional step in the Makefile. In a proper distributed project, it would be on a build server or code repo. I get what I assume is your point of view, though: that it makes it an automatic and integrated step, and potentially one hop closer to the developer that may have written in a bug.Speaking of static analysis, look at some of the examples of found faults, and you'll see stuff like this:Code:box_X = someval;box_X = someval;Code analysis would flag this for being suspicious, due to consecutive assignment. "Probably a copy and paste error." Just as likely someone carelessly using code-completion, and selecting the first entry that pops up when they've typed "box", or the impossible-to-get-right logic of the editor trying to determine whether you want to select the completion results, or navigate your editor, or whatever other action might use space / tab / Enter / arrow-keys. It's auto-correct for programmers, and is just as likely tocauseerrors as prevent them, IMO. (And here is where I will be rightly considered a hypocrite -- as Kate also supports this, and I have it enabled....)Still that's the argument I have against certain tools. Not all tools are bad -- far from it. I see the value in analysis. Boy, do I. If I happen to find something free that does a reasonable job at it, I'll start running my own code through the wringer, despite the very limited exposure anything I write will likely ever get.