[ home / board list / faq / random / create / bans / search / manage / irc ] [ ]

/prog/ - Programming

Programming board

Catalog

8chan Bitcoin address: 1NpQaXqmCBji6gfX8UgaQEmEstvVY7U32C
The next generation of Infinity is here (discussion) (contribute)
A message from @CodeMonkeyZ, 2ch lead developer: "How Hiroyuki Nishimura will sell 4chan data"
Name
Email
Subject
Comment *
File
* = required field[▶ Show post options & limits]
Confused? See the FAQ.
Embed
(replaces files and can be used instead)
Options
Password (For file and post deletion.)

Allowed file types:jpg, jpeg, gif, png, webm, mp4, pdf
Max filesize is 8 MB.
Max image dimensions are 10000 x 10000.
You may upload 1 per post.


4f6f0e No.946

I see a lot of hate for goto, a lot of places saying never to use it in your code no matter the circumstance, and a lot of languages that despite being procedural decide to completely omit the feature. There was a python module written as an April fool's day joke that implemented goto, but urged the reader to never actually use it for anything. Java treats it as a syntax error. People say that it should be avoided because it makes code harder to read and can always be replaced with structured code.

Is it that bad?

Often I find times that I want to interleave iterations of a loop with a certain operation, and this is a chore without duplicating code or introducing otherwise pointless variables.
Because of that, I find this type of code (focus on the "goto") acceptable:
#include <iostream>
#include <vector>

std::string join(std::vector<std::string> const vec, std::string const sep) {
if (vec.size() == 0) return "";

std::string result;
auto pos = vec.begin(), end = vec.end();

goto skip_separator;
while (pos != end) {
result += sep;
skip_separator:
result += *pos++;
}

return result;
}

int main() {
std::vector<std::string> vec {"a", "test", "string"};
std::cout << join(vec, " ") << std::endl;
return 0;
}

I want to know what other programmers think: is a "goto" here called for? Does it clarify or does it obscure? Consider the alternatives (duplicating the latter half of the loop body above the loop, or introducing a new variable and an if statement into the loop), are they more or less readable or expressive in your opinion? If the goto is to be avoided, which of the alternatives is preferred? Can you add a condition but have it reliably optimized out by -funswitch-loops?

What do you think?

68ae66 No.962

in your example duplicating the second half of your loop would reduce code size and improve readability.
if the second half of your loop is more than a single line of code, put it in a function and call that function before and inside the loop.
idk if goto is as bad as people say it is because I only used it a few times in BlitzBasic when I was just learning how to program, but I bet it is evil.
if apple weren't already ridiculed and hated for a thousand other reasons then people would still laugh at them for their goto fail.

btw I think you should be using iterators to iterate through vectors.

68ae66 No.963

alternatively:

while (pos != end - 1)
{
result += *pos++;
result += sep;
}
result += *pos;

79e8f6 No.964

I think in simple cases like these it's okay. The problem with the goto clause is because it causes nonnatural syntactic branching in the code. When people use it in complex cases as a replacement for more intuitive statements, it involves big headaches when debugging, refactoring and analysing.

In the specific code you're showing, introducing a new variable would be the preferred method, but understanding your use is pretty straightforward and I wouldn't kill you for something like this.

4b4c4a No.968

I think it's a case where somebody mentioned that they were evil, then new people read that and continued on without questioning it.
Also people don't like being told that something they believed was wrong.

I personally don't use them all that much, but I find it useful at times.
If there's a way to write less code, then why not?

68ae66 No.975

>>968
because it's stupid as fuck unless you used a profiler to prove that those nanoseconds you just saved did even matter in your performance-critical application.

b3a15c No.979

File: 1420074163642.png (94.27 KB, 242x210, 121:105, cs_wizard_small.png)

>>946
Daily reminder that Donald Knuth and Linus Torvalds advocate using gotos for early exit.

68ae66 No.986

>>979
yes, to unwind malloc'd data and stuff like that in the correct order when an error occurs.

68ae66 No.987

while (pos != end) {
  result += *pos++;
  result += sep;
}
result.pop_back()

btw how do I indent code like OP?

dc9faf No.1011

goto's are generally hard to read, as >>964 said.
If a kosher solution is harder to read and understand, by all means use goto.

goto got most of bad publication beause 60's programmers with assembler and flowcharts were new to using strucured blocks of code, OS subroutines aside.

>>986
You could also use RAII helpers for that. Not applicable everywhere, but saves from ~60% of headaches.

7b6dae No.1936

i blame dijkstra for all the goto hate. it's about 100 to 200 times faster than a function call, and i'm not at all shy about using them when working right down to the silicon. that doesn't mean they have a wide variety of uses, though. i practically never use them when i'm working with OO code even as "low" as C++, but they do come up.

like other people have said, if it makes the code more readable, use it. never take any of the primitive low-level tools out of your bag, no matter what anyone tells you. don't take that as a mandate to shove them in all your code, either. learn to use your tools, and apply them where they're best suited.

in goto's case, it isn't terribly common for it to be best suited to whatever task you're working on.

java treats them as a syntax error because there's no guarantee at any point of execution that the location of the goto label will be in the same spot in memory, it'd just be a "goto" in the virtual machine's memory management so it may as well be a function call. gotos in other languages like C actually turn into jumps in assembler and directly updates the instruction pointer, so that's where their advantage comes from.

even if java had hardware-supported goto functionality, i don't think people coding in java could really be trusted to use it right most of the time.

anyway, any time some one says "don't use gotos" instructionally they are speaking to shitty programmers who are just going to grow up to clobber out agile code for some shit company and never actually improve the skill as an art. that's probably why the sentiment is so strong in universities (i was told the same thing, except by those instructors who were capable of writing compilers and OS code).

7b6dae No.1937

>>946 your use of goto is fantastic. perfect example of properly using them, imo.

cdf830 No.1938

>>946

I've done this before. "lopsided" or "asymmetrical" loops. What would you call them? Sometimes a loop logically, mathematically starts in the center, and fighting it just leads to additional boilerplate shit.

Maybe a do-while loop would be clearer, since you're skipping the first check anyway. Using regular while is too analogous to an if statement.

31f95a No.1950

If goto is bad explain callback hell in babby hipster javascript libraries. Trying to debug front end code makes me want to scream.

e89a56 No.2508

Like all general rules, it's usually true but not always. The only time I personally ever use goto is to prevent masses of duplicate code for error handling. For example:


int foo()
{
if (err1)
goto error;
if (err2)
goto error;
if (err3)
goto error;

perform_important_tasks();
return 0;

error:
do_thing();
cleanup();
whatever();
return -1;
}


fd845c No.2535

> People say that it should be avoided because it […] can always be replaced with structured code.

Generally when you use goto it's because the language doesn't provide the necessary structure nor a way to add your own structures.

A lot of ugly loop and goto usage probably comes from not having a while…else structure available.


23a377 No.2542

goto is create for implemented finite state machines and other automata, centralizing cleanup code in languages w/out exceptions, breaking out of nested loops, and eliminating tail recursion. The actual kind of goto knuth was complaining about is not the kind of goto in C, but rather the much less restricted form in assembly languages.


28cfc2 No.2544

what i've noticed from myself, my friends and posts on /prog/ and /tech/ is that newbie programmers try really hard to construct legit use cases for goto.

they will actually go out of their way to write badly structured code that puts them into a corner from which they can only escape using goto.

once people have enough experience they simply don't need goto anymore, unless they're using it in the very special way in which it is used in the linux kernel, but that's not how kids use it.




[Return][Go to top][Catalog][Post a Reply]
Delete Post [ ]
[]
[ home / board list / faq / random / create / bans / search / manage / irc ] [ ]