Looking at C++: int a = 1 vs int a{1} - Page 1
Forum section: electronics / general

author: ElektroQuark
author_rank: Unknown
timestamp: November 09, 2016, 07:32:45 am
content: First steps with C++ and I see different options like:"int a = 1"or"int a{1}"Any thoughts or preferences?

author: tggzzz
author_rank: Super Contributor
timestamp: November 09, 2016, 07:57:06 am
content: There are hints in the FQA athttp://yosefk.com/c++fqa/picture.html#fqa-6.16But read the entire document so you can start thinking about more important points.(I'm particularly fond of the "const correstness" sub-section)

author: ataradov
author_rank: Super Contributor
timestamp: November 09, 2016, 07:58:17 am
content: Quote from: EdoNork on November 09, 2016, 07:32:45 amThe first one, of course. Where did the second one even come from?

author: AntiProtonBoy
author_rank: Frequent Contributor
timestamp: November 09, 2016, 08:26:10 am
content: Quote from: ataradov on November 09, 2016, 07:58:17 amIt's called the aggregate initialisation syntax. For basic POD and built-in types, i generally use assignment initialisation, but for classes and structs i do lean towards aggregate initialisation.edit:Quote from: tggzzz on November 09, 2016, 07:57:06 amThat FAQ is pretty much obsolete.C++ Core Guidelinessupersedes that.

author: ElektroQuark
author_rank: Unknown
timestamp: November 09, 2016, 08:50:58 am
content: Quote from: ataradov onTodayat 08:58:17>Quote from: EdoNork onTodayat 08:32:45The first one, of course. Where did the second one even come from?From a course from MicrosoftHERE

author: tggzzz
author_rank: Super Contributor
timestamp: November 09, 2016, 08:59:15 am
content: Quote from: ataradov on November 09, 2016, 07:58:17 amThat's one of the beautiful things about C++: it provides duplicate ways of doing simple things, so that you can write code in whatever subset of the language youpersonallyfeel like.

author: John Coloccia
author_rank: Super Contributor
timestamp: November 09, 2016, 09:00:00 am
content: Makes more sense if you see it in this form:int a = {1, 2, 3};orCode:struct s{int a;float b;char c;};s myStruct = {1, 1.23, "john"};Please don't ever do:int a{1};If for no other reason than it's ugly.Honestly, I don't really like this form of initialization at all, at least when doing it by hand. I think it can be very confusing and error prone because the meaning changes just by changing around the ordering of variables in a struct.But that said, I do find that it's very convenient for auto-generated code. Stuff like this comes up all the time when you're working with embedded controls and things like this. You have all sorts of utilities that spit out tables, maps and things like that, and this is a nice, easy way to format the output.

author: Brumby
author_rank: Unknown
timestamp: November 09, 2016, 09:26:05 am
content: Quote from: John Coloccia on November 09, 2016, 09:00:00 amThank you for an example that is useful.

author: AntiProtonBoy
author_rank: Frequent Contributor
timestamp: November 09, 2016, 09:43:28 am
content: Quote from: John Coloccia on November 09, 2016, 09:00:00 amCompilers are getting pretty good with alleviating errors. Also, I think you should probably get used to it, because this kind of initialisation (and related aggregate syntax) will be more common once structured bindings is introduced in C++17.

author: John Coloccia
author_rank: Super Contributor
timestamp: November 09, 2016, 10:26:17 am
content: Quote from: AntiProtonBoy on November 09, 2016, 09:43:28 amGet used to it? It's been part of C forever.

author: VK3DRB
author_rank: Super Contributor
timestamp: November 09, 2016, 11:15:51 am
content: Quote from: tggzzz on November 09, 2016, 08:59:15 amFor amateurs, maybe. But in a professional environment, there is only one way to code: To that which is dictated by the company's coding standards.

author: helius
author_rank: Super Contributor
timestamp: November 09, 2016, 11:32:58 am
content: Quote from: VK3DRB on November 09, 2016, 11:15:51 amWhat an elegantly obscure way to enshrine Not-Invented-Here syndrome into every project!

author: John Coloccia
author_rank: Super Contributor
timestamp: November 09, 2016, 11:50:38 am
content: Quote from: helius on November 09, 2016, 11:32:58 amI'm assuming you're not a software engineer, and the above statement perfectly illustrates why people who don't understand software should not be managing software. I suppose when you design a board at your company you just toss it together randomly and don't follow any standards, best practices or guidelines, right?

author: Brumby
author_rank: Unknown
timestamp: November 09, 2016, 11:56:49 am
content: Quote from: John Coloccia on November 09, 2016, 11:50:38 amI was thinking the same.Standards are put in place so that when you have 10 people work on a program over the years that when no. 11 opens up the source, they have some chance of following it. It also helps with site specific parameters.

author: John Coloccia
author_rank: Super Contributor
timestamp: November 09, 2016, 12:07:12 pm
content: Quote from: Brumby on November 09, 2016, 11:56:49 amYeah, exactly. Software is difficult enough as it is. Clarity and consistency are orders of magnitude more important than using every possible language feature, especially when you're dealing with a crazy, disjointed language like C++.

author: tggzzz
author_rank: Super Contributor
timestamp: November 09, 2016, 02:44:34 pm
content: Quote from: John Coloccia on November 09, 2016, 11:50:38 amI've worked at one company where the software was thrown together (the Rational ClearCase product tree showed a clear case of enzyme disorders), and which had a coding standard for the different languages in use.For C/C++ they mandated the use of the "register" keyword, even though the compiler they were using had ignored it for at least two decades.For Java, they also mandated use of the "register" keyword. 'nuff said.But yes, coding styles are helpful, especially for those languages that have to be subsetted if there is to be a hope of maintainability.

author: John Coloccia
author_rank: Super Contributor
timestamp: November 09, 2016, 02:49:34 pm
content: Quote from: tggzzz on November 09, 2016, 02:44:34 pmStuff like this drives me crazy. Stupid rules are worse than no rules. Then no one respects any of the rules because you can't tell what's real and what's neurotic. Grrrrr...

author: AntiProtonBoy
author_rank: Frequent Contributor
timestamp: November 09, 2016, 03:47:27 pm
content: Kinda amusing, because the register keyword is getting removed from newer versions of standard as well. It will be unused and reserved.

author: AG6QR
author_rank: Frequent Contributor
timestamp: November 09, 2016, 06:07:08 pm
content: Quote from: VK3DRB on November 09, 2016, 11:15:51 amUnless you work in a company that grows, and acquires others, and has a history. Software can often last longer than coding standards. When the standards change, it's rarely feasible to go back and re-write all the code to match the latest standard. When you acquire software that was developed elsewhere, to different standards, it rarely pays to rewrite it to meet your standards.I've worked on more than one project where the policy was: Use your project's standard for writing new code, but when modifying old code, use the "when in Rome, do as the Romans do" model. As you browsed through source code for a large product, you could clearly see that different areas were developed with different standards.That's one thing in favor of Python. The language itself enforces some standards (like indentation) and many others are commonly enforced by an automated tool like PEP8.Standards really do help code readability, and since most lines of code are written only once but read many times, it pays long-term dividends to write for readability. But my experience is that, with a large product and large team, if standards aren't enforced by software, it's a rare team that will strictly stick with them over the long haul.

author: Ampera
author_rank: Super Contributor
timestamp: November 09, 2016, 06:46:10 pm
content: Leaning back and drinking my Java here, eating some NetBeans from a tin.

author: donotdespisethesnake
author_rank: Super Contributor
timestamp: November 09, 2016, 06:52:07 pm
content: Coding standards are a waste of time. I've never seen a bug prevented by a coding standard.OTOH, coders who don't recognize valid syntax like "int a{1}" because "it is not in the company standard" are probably great at following rules but terrible at coding.You can't write good code by following rules, nice idea but doesn't work.

author: Lukas
author_rank: Frequent Contributor
timestamp: November 09, 2016, 08:02:46 pm
content: To my surprise, no one mentioned that the {} initializer's got new semantics. "Assignment initialisation" does silent type narrowing, i.e. a float gets truncated to an integer.The {} initializer OTOH will bark at you when it does type narrowing.

author: tatus1969
author_rank: Super Contributor
timestamp: November 09, 2016, 08:28:30 pm
content: my answer would be- use a=1 if you want your code to be easily readable by everybody. I for example know C from the early days, but only stumbled upon the second flavor some years ago. Took me a minute to understand what it meant.- use a{1} otherwise :-)

author: John Coloccia
author_rank: Super Contributor
timestamp: November 09, 2016, 11:31:19 pm
content: Quote from: donotdespisethesnake on November 09, 2016, 06:52:07 pmWith due respect, this sounds like the voice of inexperience. One of the most important things you can do when leading a software project is to have basic standards and conventions, enforce them, and have a strict process that includes a real code review and 2 eyes on everything approach. That only works efficiently if everyone does things the same way. Having one cohesive coding style means that no matter where you go in the code, and no matter who wrote it, everyone on the team can look at any piece of code and work on it very efficiently. And yes, if you go off on your own and don't follow the conventions, you will fail code review and you'll be rewriting the code.And yes, it prevents countless bugs, because countless bugs are found in code review when everyone is immediately comfortable with every piece of code they look at.It's things like this that separate the groups that seem to always produce buggy, unstable garbage and take forever to get something working from the superstars that seem to always have a rock solid code base. The former is why software is usually seen as a necessary evil and a liability as opposed to a revenue generator.I have a feeling that most people have simply never worked with a software group that's run properly so they don't really know the levels of reliability and efficiency that's possible.

author: John Coloccia
author_rank: Super Contributor
timestamp: November 09, 2016, 11:44:13 pm
content: Quote from: AG6QR on November 09, 2016, 06:07:08 pmOr taking over a pile of garbage code base! I've had to do that several times. The way I ran it was simple. All new code is done to the standard. Minor bug fixes in the old code stays the same. Major bug fixes, where you're spending weeks on it anyway, get reformatted/renamed/whatever to bring it up to snuff wherever it's practical and low risk. Eventually, a large chunk of the code base gets to be pretty good and easy to maintain, though you always end up with some old pieces of code that everyone's afraid to touch because it's so nightmarishly poorly written and fragile. For stuff like that, I usually have a wish list kicking around of little tasks that maybe take a day or two to knock off, that breaks the job up into little, manageable chunks, and it happens as a side task/branch. When things are slow and someone's looking for something to do, I'll give them one. Eventually it gets to the point that we can consider replacing that offending code the next time we go in there, and it's all been so well tested by this point that it's very low risk.It's really a thing of beauty when you have a software group that operates at high level of efficiency and it suddenly becomes an asset instead of a liability.

author: janoc
author_rank: Super Contributor
timestamp: November 10, 2016, 12:03:42 am
content: Quote from: donotdespisethesnake on November 09, 2016, 06:52:07 pmI am sorry, but I wouldn't want to be neither your colleague nor manager. Hotshot developers with views like this could be great programmers but also a disaster waiting to happen.I suggest that you read this article, perhaps it will enlighten you:https://www.fastcompany.com/28121/they-write-right-stuffThe point is not that following rules leads to good code but that following a process and a set of established rules help avoid common bad code/bugs. We are all humans and we do err. The processes and rules are there to catch this and fix the problems before they become disasters, not to be an affront to the programmers' egos. The improved quality of the resulting code is only a consequence of it.It is nothing else but basic principles of sound engineering, only applied to software.

author: Keicar
author_rank: Regular Contributor
timestamp: November 10, 2016, 01:21:53 am
content: <rant>Clarity of intent is an incredibly important aspect of coding style - and it's far more important than correctness. If you can clearly see what it'ssupposedto be doing, someone can easily fix the mistakes.Just because you need to be clever to do this stuff (and make no mistake, you do) does not suddenly transform the object of the exercise into proving how clever you are. Deploy your cleverness in ways that will actually help people - your customers, and your fellow developers.In a small shop, there may be little in the way of formal coding standards - but you've still got to have the right attitude - make your intent clear (you're not writing a novel, we don't want plot-twists, we want a narrative so hackneyed that you'll guess what's going to happen at the very beginning) and write code to be read, not just executed. Don't introduce inconsistencies to the code base without areallygood reason - and "I felt like doing it this way for a change" isn't it. Of course any good developer will have great skills at reading code, but don't challenge those skills without some sort of payoff. We all know what a joy it is to work on code that's clear and consistent - so spread the love, and give that gift to your fellow developers (and yourself, when you have to work on this stuff later).Now, I understand why people are put off by the notion of formal standards - but that's the only way to apply these principles to a large-scale project. And it's not really the standards that do the good - it's the attitudes embodied within them, and (hopefully) within the workplace culture that actually deliver the benefits.</rant>

author: AntiProtonBoy
author_rank: Frequent Contributor
timestamp: November 10, 2016, 01:39:04 am
content: Formal standards are great, provided that they are sensible and not treated as some kind of immutable thing. It should evolve and keep up with the evolution of the language itself.

author: HackedFridgeMagnet
author_rank: Super Contributor
timestamp: November 10, 2016, 01:39:57 am
content: Quote from: donotdespisethesnake on November 09, 2016, 06:52:07 pmI'm not sure I've seen a bug prevented.If you could even see one then probably you could find one that was prevented by a coding standard.Quote from: donotdespisethesnake on November 09, 2016, 06:52:07 pm?? I consider a compiler to be the implementation of a set of rules. You need to follow these rules to get your code compiled.

author: tatus1969
author_rank: Super Contributor
timestamp: November 10, 2016, 06:27:16 am
content: Quote from: donotdespisethesnake on November 09, 2016, 06:52:07 pmabsolute opposite experience of mine. the most important book for me: Safer C, Less Hatton. we introduced MISRA, and it vastly improved code quality and helped find a lot of hidden bugs that we otherwise would have rolled out.

author: tggzzz
author_rank: Super Contributor
timestamp: November 10, 2016, 08:44:26 am
content: Quote from: Keicar on November 10, 2016, 01:21:53 amVery true. Quality (and security for that matter) isn't aprocess, it is an attitude, a state of mind and a culture.An important question is how to instill the successful practices and processes in new employees. In HP, when it was Hewlett-Packard, averyimportant technique was for new employees to be told "Bill and Dave stories". These were anecdotes about what people should and should not do and aim for.Example: the store cupboard was always open, and employees were free to take components and use them for their own home projects. One Sunday Bill came in to do some work and found the there was a chain and padlock on the store. He cut the chain and left a note asking that it not be locked in future. Hewlett-Packard was good at employing people that could be trusted.Example: in the late 70s a minicomputer was shipped before it was ready, and customers complained. Packard sent a memo to the project manager (Paul Ely?)askinghim not to ship equipment before it was ready for use by customers. The manager had the memo framed and hung it on his wall - and everybody else in the company listened the message.Inculcating such attitudes takes a lot of time, and it is particularly difficult when taking over established companies. But when it works it can lead to this Fiorina-erahttp://www.satirewire.com/news/0105/loyal.shtmlkind of thing, which went around the company like wildfire!

author: VK3DRB
author_rank: Super Contributor
timestamp: November 10, 2016, 09:44:56 am
content: Quote from: John Coloccia on November 09, 2016, 11:44:13 pmJohn, you are so correct! Those who think coding standards are not important probably have little professional experience in a dynamic organisation. I have seen too many examples of garbage code with no standards written by lazy or incompetent people, managed by managers who don't know any better.A horror experience for me was fixing up 50,000 lines of rubbish in over 200 large and vaguely named .c (and .h) files written by six predecessors, five of whom did not know how to handle interrupts properly and knew nothing about clock cycles or message protocols. I know one embedded guy who saw the code and walked out within a week. It took me 18 months and almost a mental breakdown to refactor the code, and fix hundreds of major and minor bugs. If they started with coding standards, the 18 months would have been reduced to about 3 months.Another example is one guy who never even bothered indenting his code. A mix of C and inline assembly. The product was a PBX (or PABX). The bug was intermittently when a POTS phone hanged up, it would hook flash and ring back. The reason was the contact de-bounce never worked. The guy had left the company and muggins here had to find the bug. By his comments, he had tried many things to fix the fault. I spent a day trying to read his masterpiece and find the bug, so I tried reformatting the area of code where the bug could be and then I found it in five minutes. It was a line of code placed in the wrong spot in a set of deeply nested loops. Coding standards would have prevented this.Where I work (I am also in charge of a team for electronic design and embedded coding in a medical device company), we created C coding standards and PCB Altium standards that the entire team conforms to. (Anyone who has ever had to take over uncontrolled or haphazard component Altium component libraries will know what I mean.) Those standards are part of our audited SOP's, which are auditable by external authorities.Whilst having to conform to else coding standards is not everyone's liking, it is necessary. Of course, coding standards can be improved with intelligent debate and justification.Check out these coding standards...http://lars-lab.jpl.nasa.gov/JPL_Coding_Standard_C.pdfhttp://homepages.inf.ed.ac.uk/dts/pm/Papers/nasa-c-style.pdfThere are plenty of others to be found on the information superhighway.

author: ElektroQuark
author_rank: Unknown
timestamp: November 10, 2016, 10:52:12 am
content: So, int a{1} then?

author: tggzzz
author_rank: Super Contributor
timestamp: November 10, 2016, 01:22:59 pm
content: Quote from: VK3DRB on November 10, 2016, 09:44:56 amDon't underestimate the ingenuity of foolsI've seen code whereit was properly indented according to the coding rulesthe if-then-else clauses were nested 10 deepthe condition clauses mostly configured customer-specific behaviourthe release process required code review, committing to source code repositories and was thus time consuming and painfulSo the condition clauses were defined by hard-coded macros stored in a config file. Since the macro configurations are code not data, they weren't stored in the respository and could be changed without review etc. No, they couldn't see the error of their ways.Sigh. Run away.

author: rrinker
author_rank: Super Contributor
timestamp: November 10, 2016, 03:18:39 pm
content: Two examples I've been a part of, both using the same environment so the ONLY thing different was that one had a set of standards we all followed, and the other clearly never did.Case 1, with standards, I was part of a 3 person development team (they briefly hired a 4th from the same source they got me from, but he didn't last a month, he was mostly a charlatan who didn't know what he was doing). The application we worked on ran the whole business aside from accounting functions, and was extremely critical. Additions and modifications took place quickly and accurately. Bugs were few and far between, and when found, easily fixed. The app evolved swiftly as the needs of the business changed, and we had no problem keeping up with expectations and timelines. We also had a formalized dev/test/prod structure which kept things in line and prevented any major faults from getting to production.Case 2 I was not initially involved in the application. I was brought in because people who have experience in the environment are few and far between these days (Visual Foxpro, in case anyone was interested). The application stretches back to the early DOS days of dBase IV and Clipper, and has had a whole raft of different programmers working on it, with no standards, to the point of the app being a virtual museum of how the products themselves evolved over time, adding new language extensions while retaining compatibility with the oldest forms as well. This application is also mission critical, a full ERP system, and it's FULL of bugs. It takes forever to track anything down due tot he convoluted nature of the various modules, and when you do find the bug, it's not always a straightforward fix - making the logical change often results in fixing the bug but breaking another component, so you end up doing all sorts of conditional coding to fi the identified bug without causing other unintended consequences. I do enjoy the challenge, for a while, then it just becomes tiring.