C++: Redirect code to certain position - c++

I am very new to C++.
How I can "redirect" code to certain position?
Basically, what should I put instead of comments lines here:
if ( N>1 ) {
// What should be here to make the code start from the beginning?
}
else {
// What should be here to make the code start from certain point?
}
I understand that C++ is not scripting language, but in case the code is written as script, how I can make redirect it?
Thank you

A goto command will do what you want but it's generally frowned on in polite circles :-)
It has its place but you would be possibly better off learning structured programming techniques since the overuse of goto tends to lead to what we call spaghetti code, hard to understand, follow and debug.
If your mandate is to make minimal changes to code which sounds like it may already be badly written, goto may be the best solution:
try_again:
n = try_something();
if (n > 1)
goto try_again;
With structured programming, you would have something like:
n = try_something();
while (n > 1)
n = try_something();
You may not see much of a difference between those two cases but that's because it's simple. If you end up with your labels and goto statements widely separated, or forty-two different labels, you'll beg for the structured version.

Use functions, loops etc to control the "flow" of your application. Think about code as reusable pieces, anything that is going to be reused should be placed in a function or looped through.
Here is an example:
void main()
{
int i = 0;
SayHello();
if (i < 1)
{
SayHello();
i++;
}
else
{
SayGoodbye();
}
}
void SayHello()
{
cout << "Hello" << endl;
}
void SayGoodbye()
{
cout << "Goodbye" << endl;
}

I'm not entirely certain what you mean by "redirect", but consider the following:
if (N > 1) {
speak();
} else {
do_something_else();
}
as paxdiablo has already stated the goto method isn't good practice. It would be better to use functions that do a specific thing, this way debugging is easier and someone can actually follow what your code is doing (or at least what it is supposed to do).

Related

C++ - Pointer to local variable within the function

I know this can look like a rookie question already asked a thousand time. But I searched for the exact answer and I haven't found one...
I'm working on a code that, to sum up, fill an XML with different data.
I'm trying to optimize a part of it. The "naïve" code is the following:
xml << "<Node>";
for(auto& input : object.m_vec)
{
if(input == "Something")
{
xml << input;
}
}
xml << "</Node>";
for(auto& input : object.m_vec)
{
if(input == "SomethingElse")
{
xml << "<OtherNode>";
xml << input;
xml << "</OtherNode>";
break;
}
}
The important thing is, while more than one input fit in <Node></Node>, only one fit in <OtherNode></OtherNode> (explaining the break;) and it may not exist either (explaining the xml << in-between the if statement).
I think I could optimize it such like:
std::vector<std::string>* VecPointer;
xml << "<Node>";
for(auto& input : object.m_vec)
{
if(input == "Something")
{
xml << input;
}
else if(input == "SomethingElse")
{
VecPointer = &input;
}
}
xml << "</Node>";
if(!VecPointer->empty())
{
xml << "<OtherNode>"
<< *VecPointer
<< "</OtherNode>";
}
The point for me here is that there is no extra memory needed and no extra loop. But the pointer to the local variable bothers me. With my beginner's eyes I can't see a case where it can lead to something wrong.
Is this okay? Why? Do you see a better way to do it?
You need to make sure your compairson also looks for an existing value within the VecPointer, since your original second loop only cares about the first value it comes across.
else if(VecPointer && input == "SomethingElse")
Don't look for ->empty(), as that's accessing the pointer and asking whether the pointed to vector is empty. If there's nothing to point to in the first place, you're going to have a bad time at the -> stage of the statement. Instead, if against it, since it's a pointer.
if(VecPointer)
Finally, you're using a Vector to save that one value from m_vec, which from other code I'm assuming is not a vector<vector<string>> but a vector<string> - in the latter case, your VecPointer should be std::string*
std::string* VecPointer = nullptr;
I'm trying to optimize a part of it.
...
Is this okay?
Maybe not! This may already be a poor use of your time. Are you sure that this is what's hurting your performance? Or that there's a performance problem at all?
Remember Don Knuth's old adage: Premature optimization is the root of all evil...
Do you see a better way to do it?
Consider profiling your program to see which parts actually take up the most time.
On an unrelated note, you could use standard library algorithms to simplify your (unoptimized) code. For example:
if (std::ranges::find(std::begin(object.m_vec) std::end(object.m_vec), "SomethingElse"s )
!= std::end(object.m_vec))
{
xml << "<OtherNode>" << whatever << "</OtherNode>";
}

Clean coding: how to break loops from inside a function call inside a loop

Clean coding principles generally include a rule that functions must be small and single-purpose.
From Robert Martin's book, Clean Code: "The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that."
This is difficult to adhere to if I have a function with a complicated loop that contains branches that can break the loop. For example, this code in a chess variant is meant to allow a unit to attack by leaping over another unit on the board:
for (arow = row, acol = col - 1, found_obstacle = false; acol >= 0; --acol) {
if (!found_obstacle) {
if (cellHasUnit(arow, acol)) found_obstacle = true;
continue;
} else {
if (cellHasUnit(arow, acol)) {
if (!cellHasAlly(arow, acol))
_dangerzones.insert(std::make_pair(arow, acol));
break;
}
}
}
I understand that you cannot break a loop from inside a function, where the function is called inside that loop.
What is a good way to handle complicated break conditions inside loops in order to maintain clean code with short functions? I can imagine using a special function with a return value to indicate if breaks are necessary, but that still means that each break needs its own function. If I have many break conditions that means the function containing the main loop would still be quite big.
Edit: I am asking the general question of whether it is practical and desirable (from a clean coding perspective) to modularize within-loop code that has a number of break conditions.
As a programmer with above 15 years of programming in several programming languages, I can first tell you that the quote you brought is very nice, you should follow it in order to make modular code, but it doesn't mean each function should be 10 lines of code. That's impossible.
Regarding your code, it is OK. Not complicated. You use functions inside the loop and it looks modular. A break is also OK.
I have one comment, though, using continue looks redundant. You could do:
if (cellHasUnit(arow, acol)) {
found_obstacle = true;
else {
...
Some discourage continue altogether because it can confuse. I don't follow this recommendation and sometimes use continue but I do try to avoid both break and continue on the same loop because they have somewhat opposite meanings.
Maybe at the break; statement, set acol = -1 and then continue; so that on the next iteration, you break out of the loop?
You may find this form more expressive. It inverts the tests and therefore avoids 2 call sites for the cellHasUnit test:
#include <map>
std::map<int, int> _dangerzones;
bool cellHasUnit(int, int);
bool cellHasAlly(int, int);
void handleAlly(int arow, int acol)
{
if (!cellHasAlly(arow, acol))
_dangerzones.insert(std::make_pair(arow, acol));
}
void test(int row, int col)
{
int arow = row;
bool found_obstacle = false;
for (int acol = col - 1 ; acol >= 0 ; --acol)
{
if (cellHasUnit(arow, acol))
{
if (found_obstacle)
{
return handleAlly(arow, acol);
}
else // not strictly necessary
found_obstacle = true;
}
}
}
The return statement is used to indicate that in this example, the breaking of the loop is also necessarily the end of the test function.
If the real function is longer, then you could write this instead:
if (found_obstacle)
{
handleAlly(arow, acol);
break;
}
else ...

Creating an Interactive Prompt in C++

I have a program which should read commands from the console and depending on the command perform one of several actions. Here is what I have so far:
void ConwayView::listening_commands() {
string command;
do {
cin >> command;
if ("tick" == command)
{
// to do
}
else if ("start" == command)
{
// to do for start
}
...
} while (EXIT != command);
}
Using a switch in place of the if statements helps a little if there are a large amount of commands. What patterns do you suggest using to provide the interactive command line?
There are multiple ways to solve this and it's debatable what the "right" solution is. If I were to solve it for my own work, I would create a table of a custom struct. Something like:
struct CommandStruct {
char *command;
int (*commandHandler)(/*params*/);
} commandTable[] = {
{ "tick", tickCommand },
{ "start", startCommand },
...
};
Then my processing loop would walk through each element of this table, looking for the right match, such as:
for (int i = 0; i < TABLE_SIZE; ++i) {
if (command == commandTable[i].command) { /* using whatever proper comparison is, of course */
commandTable[i].commandHandler(/*params*/);
break;
}
}
Not really a pattern, but often a good approach:
#include <map>
#include <functional>
#include <string>
#include <iostream>
typedef std::map< std::string, std::function<void(void)> > command_dict;
// ^^^^^^^^
// the signature of your commands. probably should have an error code.
void command1() { std::cout << "commanda" << std::endl; }
void command2() { std::cout << "commandb" << std::endl; }
void command3() { std::cout << "commandc" << std::endl; }
int main() {
command_dict c;
c["a"] = &command1;
c["b"] = &command2;
c["c"] = &command3;
std::string input;
while(std::getline(std::cin, input)) { // quit the program with ctrl-d
auto it = c.find(input);
if(it != end(c)) {
(it->second)(); // execute the command
} else {
std::cout << "command \"" << input << "\" not known" << std::endl;
}
}
}
If the number of command is small and possible parameters are really few, you could keep on with switch case !
If the number of commands increases, consider the command design pattern (which is IMHO some sort of strategy pattern disguised: cf Using a strategy pattern and a command pattern for the differences between command and strategy patterns).
If most of your commands are all sharing a part of the same behaviour, don't forget the template method pattern.
If the complexity for creating your command objects increases ( i.e. there is complexity in decoding/understanding the input of your command line), you should start looking at the interpreter design pattern
If while designing with the help of the interpreter pattern, you happen to see some complexity ( if the interpreter needs too much work, you see syntax issues and so on ), then you should probably look at DSL, domain specific language, and design your own language that fits (and only fits) to you own inputs.
The if-else ladder is fine.
It can in principle be replaced with a map<string, Function>, but that gains you nothing for this concrete case (it is added complexity for no particular gain, even with a high number of commands).
When I wrote this initially I forgot to mention though:
Make your command handlers separate functions.
If you don’t, then the if-else ladder can become quite messy… The map solution requires separate functions, and can therefore appear to be a little more clean than an everything-directly-here if-else ladder. But it’s really the separate functions that then provide a measure of clarity, while the map detracts a little (adding extra work in maintaining the map, and an extra level of indirection to cope with).
On the other hand, since “read commands from the console” indicates interactive input, with a user in the picture, you don’t want to read two or more commands from the same line of input. Because that would screw up the prompting, and can seem quite baffling to the user. So instead of reading a “word” of input at a time using >>, use std::getline to a read a full line of input at a time.
Use the new and improved way to preform a bunch of commands at will:
int happy_time = 5;
int a = happy_time;
int muddy_dirt = 1;
int b = muddy_dirt;
int c = happy_time * muddy_dirt //really messy stuff
that's probably the least complicated way to do it...
You must use database like access if your command is large.

Can you rewrite this snippet without goto

Guys, I have the following code that is inside a big while loop that iterates over a tree. This is as fast as I can get this routine but I have to use a goto. I am not fundamentally against goto but if I can avoid them I would like to. (I am not trying to start a flame war, please.)
The constraints:
The current=current->child() is expensive (it's a shared_ptr) so I'd like to minimize the use of that operation at all cost.
After the operation current should be the last child it found.
cnt must count each child it encounters.
cnt++ will be replaced by some other operation (or several operations) and should only appear once :)
the code:
insideloopy:
cnt++;
if ( current->hasChild() )
{
current = current->child();
goto insideloopy;
}
Edit: Sorry guys, originally forgot to mention cnt++ should only appear once. It will be some kind of operation on the node, and should thus only be there one time. I'm also trying to avoid making that another function call.
Original answer
Assuming this is C or C++:
while (cnt++, current->hasChild())
{
current = current->child();
}
I'm not a big fan of the comma operator usually, but I don't like repeating myself either :)
Updated 'fun' answer
After learning that cnt++ is actually some multiline operation, this particular syntax would be less than ideal. Something more along the lines of your accepted answer would be better.
If you want to be really funky, this would also work:
do
{
cnt++;
} while (current->hasChild() && (current = current->child()));
Now I feel really dirty though, with my abusing the short circuiting on the && operator :)
Sane answer
Exercises in compactness aside and striving for readable code, I'm forced to conclude that one of the existing answers is best suited (I'm just including this for completeness' sake):
while (true)
{
cnt++;
if (!current->hasChild()) break;
current = current->child();
}
The while (true) will be optimized by the compiler into a regular infinite loop, so there is only one conditional statement (if you care about that).
The only thing going against this solution is if your node operation was a long piece of code. I don't mind infinite loops so much, as long as I can see where they terminate at a glance. Then again, if it were really long, it should be a function anyway.
cnt++;
while(current->hasChild())
{
cnt++;
current = current->child();
}
EDIT:
If you only want cnt++ to be in your code once:
while(true)
{
cnt++;
if(current->hasChild())
current = current->child();
else
break;
}
insideloopy:
cnt++;
if ( current->hasChild() )
{
current = current->child();
goto insideloopy;
}
I love infinite loops.
while (true) {
cnt++;
if (!current->hasChild()) break;
current = current->child();
}
Of course you can do it in many other ways (see other answers). do while, put the check in the while, etc. In my solution, I wanted to map nearly to what you are doing (an infinite goto, unless break)
You can use break to get out of the loop in the middle of the code:
while (true) {
cnt++;
if (!current->hasChild()) break;
current = current->child();
}
while (current->hasChild())
{
cnt++;
current = current->child();
}
Or am I missing something?
for(cnt++ ; current->hasChild() ; cnt++) {
current = current->child();
}
I'd investigate the possibility of making current->child() return NULL when it has no child if it doesn't already -- that seems the best possible result and leaving it undefined in this case seems error prone -- and then use:
for (; current; current = current->child())
{
cnt++;
}
No break statements:
notDone=true;
while(notDone){
cnt++;
if ( current->hasChild() ){
current = current->child();
} else {
notDone=false;
}
}

Why are empty expressions legal in C/C++?

int main()
{
int var = 0;; // Typo which compiles just fine
}
How else could assert(foo == bar); compile down to nothing when NDEBUG is defined?
This is the way C and C++ express NOP.
You want to be able to do things like
while (fnorble(the_smurf) == FAILED)
;
and not
while (fnorble(the_smurf) == FAILED)
do_nothing_just_because_you_have_to_write_something_here();
But! Please do not write the empty statement on the same line, like this:
while (fnorble(the_smurf) == FAILED);
That’s a very good way to confuse the reader, since it is easy to miss the semicolon, and therefore think that the next row is the body of the loop. Remember: Programming is really about communication — not with the compiler, but with other people, who will read your code. (Or with yourself, three years later!)
I'm no language designer, but the answer I'd give is "why not?" From the language design perspective, one wants the rules (i.e. the grammar) to be as simple as possible.
Not to mention that "empty expressions" have uses, i.e.
for (i = 0; i < INSANE_NUMBER; i++);
Will dead-wait (not a good use, but a use nonetheless).
EDIT: As pointed out in a comment to this answer, any compiler worth its salt would probably not busy wait at this loop, and optimize it away. However, if there were something more useful in the for head itself (other than i++), which I've seen done (strangely) with data structure traversal, then I imagine you could still construct a loop with an empty body (by using/abusing the "for" construct).
OK, I’ll add this to the worst case scenario that you may actually use:
for (int yy = 0; yy < nHeight; ++yy) {
for (int xx = 0; xx < nWidth; ++xx) {
for (int vv = yy - 3; vv <= yy + 3; ++vv) {
for (int uu = xx - 3; uu <= xx + 3; ++uu) {
if (test(uu, vv)) {
goto Next;
}
}
}
Next:;
}
}
I honestly don't know if this is the real reason, but I think something that makes more sense is to think about it from the standpoint of a compiler implementer.
Large portions of compilers are built by automated tools that analyze special classes of grammars. It seems very natural that useful grammars would allow for empty statements. It seems like unnecessary work to detect such an "error" when it doesn't change the semantics of your code. The empty statement won't do anything, as the compiler won't generate code for those statements.
It seems to me that this is just a result of "Don't fix something that isn't broken"...
Obviously, it is so that we can say things like
for (;;) {
// stuff
}
Who could live without that?
When using ;, please also be aware about one thing. This is ok:
a ? b() : c();
However this won't compile:
a ? b() : ; ;
There are already many good answers but have not seen the productive-environment sample.
Here is FreeBSD's implementation of strlen:
size_t
strlen(const char *str)
{
const char *s;
for (s = str; *s; ++s)
;
return (s - str);
}
The most common case is probably
int i = 0;
for (/* empty */; i != 10; ++i) {
if (x[i].bad) break;
}
if (i != 10) {
/* panic */
}
while (1) {
; /* do nothing */
}
There are times when you want to sit and do nothing. An event/interrupt driven embedded application or when you don't want a function to exit such as when setting up threads and waiting for the first context switch.
example:
http://lxr.linux.no/linux+v2.6.29/arch/m68k/mac/misc.c#L523