Why is it not good practice to use 'goto'? [duplicate] - c++

This question already has answers here:
What is wrong with using goto? [duplicate]
(6 answers)
Closed 5 years ago.
I read in the book I am learning C++ from about loops and it taught be goto first, but near the end it said not to use it, as it was bad practice, and said it created 'spaghetti' code. I don't understand what that means and why it is bad. Could someone please explain?

Spaghetti is a code poorly structured and which makes it hard to update because of multiple undocumented and unexpected links or dependencies. You touch it in one place and you see other things get broken or modified in an unexpected way. Just like sticky spaghetti, you pull one end and you see a number of places start moving.
GOTO usually violates the principles of structured, procedural programming, hence the term, which suggests the tangled and arbitrary nature of the program flow.

Related

Python 3.5 Lists management [duplicate]

This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 6 years ago.
My question is not related to a problem, as such, but I looked at several python scripts, like the one below:
''.join([i if ord(i) < 128 else '' for i in text])
The list is built on a loop and contains an IF statement. I tried to find in the documentation the structure of such formula (e.g why put the IF in front and the FOR at the end). I am trying to understand the logic behind, in order to be able to build and develop my own formula. Unfortunately, despite all the documentation I looked on the net and books I bought, the information was pretty basic (usually they use enumerated lists and that's it). Could any of you give me a link to a doc that would be a bit more explicit on this topic ?
I recently discovered the dict(zip(a,b))-way to build dictionary, but the lack of understanding of this topic keeps me behind...
Best Regards,
Those are List Comprehensions and are pretty much a condensed for loop to cover common loop patterns with less code. ( https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions )

Adding a namespace vs adding std:: to every line of code [duplicate]

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 6 years ago.
I've been coding for many years as a hobby and I'm now studying computer science which is a great way to answer the "why"s as well as the "how"s of the programming world. I've seen many great code examples across multiple message boards including this one and I'm wondering why some people would rather add "std::" to every single line of code rather than just adding "using namespace std;" once and never having to worry about it ever again. I understand some projects involve multiple namespaces, but what about the ones that only use "std::"? I hope someone might be able to shed some light on this, and I'm sorry if this comes off as a dumb question.
Thanks!
Well, if it is not a matter of coding style, people including myself here usually goes to "std::" to avoid name collisions that may happen when you start "using" a few namespaces in your code.
By specifying the entire scope (ex "std::string") of a type you are reducing the name collision risk to pretty much zero.

Problems with inheritance in the STL [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In http://www.stepanovpapers.com/notes.pdf, Alexander Stepanov mentions:
It is interesting to note that the only examples of inheritance that
remained in STL inherit from empty classes. Originally, there were
many uses of inheritance inside the containers and even iterators, but
they had to be removed because of the problems they caused.
What are the technical problems that precluded the use of inheritance in the STL?
I think I will put some comments directly from Alexander Stepanov (http://www.stlport.org/resources/StepanovUSA.html).
Question:
STL is full of creative uses of templates, such as symbolic
types exported from classes, or the pattern matching of a set of
overloaded algorithms onto iterator tags. Surely enough, no standard
C++ Programming book speaks about those idioms. How did you come to
these C++ code idioms?
Answer:
I knew exactly what I was trying to accomplish. So I tweaked
the language until I was able to get by. But it took me many years to
discover all the techniques. And I had many false starts. For example,
I spent years trying to find some use for inheritance and virtuals,
before I understood why that mechanism was fundamentally flawed and
should not be used. I am very happy that nobody could see all the
intermediate steps - most of them were very silly. It takes me years
to come up with anything half decent. It also helped that Bjarne was
willing to put certain features in the language just to enable some of
my idioms. He once refered to it as "just in time language design."
Next, I will allow myself to direct you to this great answer:
https://stackoverflow.com/a/1039904/210971
OOP is not the holy grail. It's a cute idea, and it was quite an
improvement over procedural languages back in the 70's when it was
invented. But it's honestly not all it's cracked up to be. In many
cases it is clumsy and verbose and it doesn't really promote reusable
code or modularity.
That is why the C++ community is today far more interested in generic
programming, and why everyone are finally starting to realize that
functional programming is quite clever as well. OOP on its own just
isn't a pretty sight.
And now something from me:
OOP rules dictates the way (inheritance, polymorphism, etc.) a programmer thinks about interaction between things (objects, entities, tribbles, etc.).
This is clearly visible in this simple Java example from time before adding support for generics (but these are not as verbose as in C++).
List v = new ArrayList();
v.add("test");
Integer i = (Integer)v.get(0); // Run time error
Although the code is compiled without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.
List<String> v = new ArrayList<>();
v.add("test");
Integer i = v.get(0); // (type error) compilation-time error
Alexander Stepanov recognized that generic approach can solve this issue, help in providing logical separation (abstraction) between data structures and algorithms. This is why there is so much emphasis on iterators, functors, and many other idioms that fit very well into generic world.

Why and when should a goto be used in C / C++? [duplicate]

This question already has answers here:
Examples of good gotos in C or C++ [closed]
(16 answers)
Closed 9 years ago.
I know lots of questions about why not use goto, why goto is bad practice, why goto was create by devil, why the fingers of those who type goto should be ripped off, etc...
And in many answers to this questions , this question, and even at wikipedia it's possible to find reasons pro / against goto.
Even Stackoverflow has a goto tag :)
But, obviously, goto is accepted as a valid command, otherwise your compiler / interpreter wouldn't know what to do with it. Even in C / C++ it's possible to use goto, and that language even has a formal, ISO specification.
So, probably, there should be some case where only by using goto it's possible to accomplish some task. Then, why and when should a goto be used in C / C++ ?
Edit:
Just to make sure:
1 - this question doesn't require debate. It should be answerable: giving one or more cases where goto is the only solution, or stating no, it's always possible to avoid a goto. Of course, I'm not the only who can decide whether it should be closed or not, but I don't think that "too broad, asks for debate, etc" are reasons to close it.
2 - There might be some cases where goto make the code cleaner, faster, etc. I don't want those. I want to know if there exists one case where goto is the only solution (no, it's not a dup of that "give good examples of goto" question)
3 - I'll accept any downvote, with a smile on my face, if the downvote is justified. But I'm pretty sure that this question has an answer and has done previous research about the subject. Downvoting simple because those 4-letters taboo word that starts with a "G" was used... sorry...
There is no circumstance under which a goto is strictly necessary: you can always avoid it if you really want to, but to do that for purely idealogical reasons is a mistake.
For example, a friend of mine wrote a wavelet transform function that had (something like) 15 nested loops. In the event of an error in those loops, he had a goto to a cleanup block just before the function's return statement. To achieve the same effect without a goto would have involved setting a flag and testing it at every loop level, which would have made his code far less readable. In these circumstances, goto was the right choice.
The latest MISRA standard now allows gotos.
A good example where gotos make sense is when you have a large routine with a lot of exits points. You can have many return statements (not good) convolute the code with 'structured programming' conditionals (also not good) or a "goto Done; which sends the program to a set of ending statements before returning.
The MISRA standard basically allows gotos for these sort of circumstances. I think 'only downward' is one of their criteria.
The only reason I use a goto is when it is for an error return condition from a function that needs some common cleanup. The target of the goto is near the end of the function and the "normal" return returns before the label.
Here is an example where only goto will work:
https://stackoverflow.com/a/245801/193848
Basically if you have multiple nested for loops, the only way to break out of all the loops from an inner loop is with a goto statement (since unlike some other languages the C break keyword doesn't support a parameter for the number of nesting levels to break out).

Is it acceptable for a C++ programmer to not know how null-terminated strings work? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is there any way for a C++ programmer with 1,5 years of experience to have no idea that null-terminated strings exist as a concept and are widely used in a variety of applications? Is this a sign that he is potentially a bad hire?
Is there any way for a C++ programmer
with 1,5 years of experience to have
no idea that NULL-terminated strings
exist as a concept and are widely used
in a variety of applications?
No. What have he/she been doing for these 1,5 years?
Is this a sign that he is potentially
a bad hire?
Yes. Knowledge of C should be mandatory for a C++ programmer.
What does he use -- std::string only? Does he know about string literals? What is his take on string literals?
There's too little detail to tell you if he's a bad hire, but he sounds like he needs a bit more talking to than most.
Is this a sign that he is potentially a bad hire?
Definitely, C++ programmer must understand what happens behind all cool STL stuff.
Unfortunately there are too many substandard C++ programmers on the market.
BTW: The are not NULL terminated, but rather zero terminated.
IMHO, I'd expect a competent programmer to have the basic curiosity to wonder how things like the STL containers actually work. I wouldn't expect them to necessarily be prepared to implement one, mind you.
But the NUL terminated string is a fundamental data type of both C and C++. Given the chance to avoid the messy details with a container is a luxury. You still have to appreciate what the container is doing for you.
I'd say it depends on what you want to hire them for, and what their purpose in your organization will be.
Somebody who understands C++ but not C (which is easy to do, nowadays), will fall into this type of category. They can, potentially, be a fine employee. However, I would say this is a warning, so depending on their resume, this would be one mark against them in my book.
However, if they are going to be working on fairly straightforward projects, and not be required to design and develop critical parts of your code base (at least early on), they might be fine.
I would not, however, hire somebody to do design or to work on critical systems who did not understand the basic concepts like this one. Any developer I hire who will be working on C++ projects at a high level needs to understand memory management, basic concepts of C and C++, templates and generic programming, and all of the fundamentals, at least to a reasonable degree, of the language they will be using.
Not understanding the concepts of how string literals work would be a big disadvantage - even if they will be using std::string or the like, I want them to understand how it works underneath, at least to some degree, and also the other options out there. Understanding the concepts helps to understand the rationale behind the newer, nicer technologies, but also to understand the compromises being made when they are used. It also helps to understand the design decisions made there, and apply them to your own projects.
In the work we do at my company, and I guess that is the case for many other places, you must know about NULL-terminated (or zero terminated) strings. Yes, we use C++ and we try to use std::string where we can. But we have code that was developed years ago that uses C-style strings, sprintf and this kind of stuff. Then you have external code and APIs, how can you call even Windows API without knowing about these C concepts?
So will he be a bad hire? Well, what you don't know you can learn... But it is definitely not a good sign.
NUL-terminated strings (aka ASCIIZ) aren't even a C construct, I think a good programmer should at least know there are different ways to store a string (terminating with 0, prefixing with length...).
Perhaps you won't ever need this, but for me it feels like using your computer without ever opening it and have a look what's in there just to understand it a bit better.
I won't say that someone who doesn't know about it is potentially a bad hire, but note that if you use NUL-terminated strings in your project, he'll have to learn the concept and might stumble about the common mistakes in this field (not increasing the array sizes by 1 to store the additional 0 etc.) which a programmer that knows about NUL-terminated string wouldn't.
not knowing that they exist - a really bad sign
hardly using them - IMO not really a bad sign. Back in the days when I was programming C++ I avoided null terminated strings for everyting except for string literals.
std::strings (or CStrings) were used instead.
It means they have never opened a file forv input or output. The standard library has no means of specifying a file name via a std::string - you have to use a zero-terminated one.
It sounds like this is a programmer who didn't start out as a programmer. I took C++ classes in college and even read a few books on the language. Every book within the first 3 chapters will explain how a string, which is an array of characters, knows that it ends, by using the "/0" identifier. This is basic knowledge of C++.
This programmer sounds like a business user who wanted to cut costs by learning "programming" in order to create software for the company without getting a properly educated and experienced developer.
Sorry if that sounded harsh. I take my profession very seriously and consider it an art form of sorts.
Consider the coursework in any C/C++ based undergrad coursework. There has to be a data structures course s/he must have taken and this course must have had an assignment wherein they have to implement a string type from scratch. Obviously, nobody expects all functionality of std::string but they must have implemented a string class and when they did that they must have explored this matter, in depth.
No hire.
People say and do all sorts of weird things while being interviewed. Have you seen this person do any coding?
1.5 years is not very much time, but experience means squat if the hire can't think properly. So I'd note it as a warning flag and dig deeper. If the interviewing stage is over and you have to make a decision, it sounds to me like your answer should be NO HIRE.
I'd say that it depends on what you are looking for. If you're looking for a relatively inexperiences (and therefore presumably cheap) programmer that you can mold to fit your organization, he might be OK. You've just found out that he has no idea how C does things, and that you'll have to explain a whole lot of C concepts to him when they come up.
At this point the important thing is to figure out if he's just uneducated (he's never come across the need before) or if he's he kind of guy who never learns ANYTHING he doesn't immediately need, or if he's an idiot. If #1, then you can consider hiring him, if he knows enough to be useful. If #2 then I'd take a pass, but perhaps you can make use of a 9-5er. If #3, show him the door.
And I wouldn't take not knowing about C stuff TOO seriously, I've met people who've programmed in C for 15 years who didn't know about __FILE__ and __LINE__. And they were good, they just never came across it before I showed it to them. This guy could be the same way – he's only ever seen the STL way of doing things, so he doesn't know anything else.
In your hiring decision, you should consider whether or not he will be able to learn the important pieces of information over whether or not he knows them now. A year and a half is hardly any time at all as far as business experience goes. As others have mentioned, dig deeper, try to find the boundaries of his programming knowledge, and try to figure out how hard it will be to push those boundaries outward. This will depend a lot on personal habits and character. If he's a good learner and a good communicator, he's a good hire. If technical learning is beyond him, programming probably isn't the best career for him.
Well, I heard from a friend in German SAP they they hired someone as a developer and then later discovered he had always thought 1KB = 1000 Bytes. Looks like they discovered it when he made some kind of bug. They were shocked then moved him to do customer support.
Compared to that, your newly hired developer could be a genius. If seriously, he could have just started making his experience when high-level languages occupied the majority of the market and just didn't skim the era of low-level programming (C++ or something).
Does not necessarily mean he is bad. Just belongs to the new pepsi-generation of developers.
NULL-terminated strings don't exist, so I guess he might be a good hire.
Update: null-terminated and terminating '\0' appear in the C++ standard, according to some of the comments. Instead of deleting my answer, I turn it into wiki, to preserve the interesting part of the debate.