I'm pretty new to c++, and I was told not to use a 'break' statement. I was curious what are some alternatives to a 'break'? (using the example of the code below)
void remove_comments( ifstream& fileIn , ofstream& fileOut)
{
string line;
bool flag = false;
bool found = false;
while (! fileIn.eof() )
{
getline(fileIn, line);
if (line.find("/*") < line.length() )
flag = true;
if (! flag)
{
for (int i=0; i < line.length(); i++)
{
if(i<line.length())
if ((line.at(i) == '/') && (line.at(i + 1) == '/'))
break;
else
fileOut << line[i];
}
fileOut<<endl;
}
if(flag)
{
if(line.find("*/") < line.length() )
flag = false;
}
}
}
In my opinion using break is quite OK but if your task is to do the job without it then let's do this without it. The very same problem can be solved by using several differently structured codesnippets that use different control flow statements from C++. This problem can also be solved without break. I recommend you to break your function into a central function and several helper functions. Since I don't want to solve the problem instead of you I help just with instructions and with some "pseudo code"-ish something.
You have an input text that consists of commented and noncommented sections in turns. You want to do the following in a loop:
// I refer to non-commented text as "writable"
writable_begin = 0
while (writable_begin < text_len)
{
writable_end, comment_type = find_next_comment_begin(writable_begin);
write_out_text(writable_begin, writable_end);
if (comment_type == singleline)
writable_begin = find_singleline_comment_end(writable_end);
else
writable_begin = find_multiline_comment_end(writable_end);
}
You have to find out how to implement the helper functions/methods I used in my pseudo code, they can easily be implemented without break. If you solve the problem with helper functions you also get a much nicer looking solution than your current spaghetti code that uses complex control flow statements. Many bugs can easily hide in such code.
Tip: Your helper functions will search the end of the commented text in a loop but instead of break you can simply use return to exit the helper func with the result.
You could rewrite the loop
for (int i=0;
i < line.length() &&
!(i+1 < line.length() && (line.at(i) == '/') && (line.at(i + 1) == '/'));
++i)
{
fileOut << line[i];
}
fileOut<<endl;
Breaking is sometimes necessary -- without breaks you might crash into the stuff ahead and hurt yourself.
You may also hurt yourself by thinking poorly and then solving the problem in a cryptic manner that even you won't understand 6 months later.
Lastly -- whoever told you not to use a "break" .. give him a break -- never stop by him/her/it for advise.
BTW -- work on your indentation and curlies -- not good.
You could - and should - rewrite that loop. Mankarse showed one option, but that's got all those weird and difficult to understand conditions in the for loops.
You should learn to leverage the power of the standard library. For example, this code will remove all the characters that follow a C++ style line comment from the string stored in line:
// Find the first instance of two forward slashes in the line
// and return an iterator to that.
auto begin_comment = line.find("//");
// We found it! Remove all characters from that point on
if (begin_comment != std::string::npos)
line.erase (begin_comment, line.end());
fileOut << line << std::endl;
Consider how you could also take small chunks of code like that and put them into functions, which you will call to do work on your behalf. This will not only keep the code more readable, but it will get you into the habit of designing interfaces, which is a very important skill to have.
As a sidenote, your indentation is really bad and you must work on it. Look at this gem:
for (int i=0; i < line.length(); i++)
{
if(i<line.length())
if ((line.at(i) == '/') && (line.at(i + 1) == '/'))
break;
else
fileOut << line[i];
}
Which of those two if statements does the else match up against? Are you immediately and completely sure that you are right?
To be sure, the compiler doesn't need indentation and couldn't care less for it. But you do, and you will soon find out that as your code grows more complex, unless it's properly indented, it will be impossible to understand.
Related
I am copying code of file 1 to file 2 , but i want the code in file 2 to look adjusted with indentation like this: at the beginning indentation=0, every curly bracket opened increases the depth of indentation, every curly bracket closed reduces the indentation 4 spaces for example. I need help in fixing this to work
char preCh;
int depth=0;
int tab = 3;
int d = 0;
int pos = 0;
file1.get(ch);
while(!file1.eof())
{
if(ch=='{')
{
d++;
}
if(ch=='}'){
d--;
}
depth = tab * d;
if(preCh == '{' && ch=='\n'){
file2.put(ch);
for (int i = 0; i <= depth; i++)
{
file2.put(' ');
}
}
else
file2.put(ch);
preCh = ch;
ch = file1.get();
}
}
result must be indented like in code editors:
int main(){
if(a>0)
{
something();
}
}
Maybe, unexpectedly for you, there is no easy answer to your question.
And because of that, your code will never work.
First and most important, you need to understand and define indentation styles. Please see here in Wikipedia. Even in your given mini example, you are mixing Allman and K&R. So, first you must be clear, what to use.
Then, you must be aware that brackets may appear in quotes, double quotes, C-Comments, C++ comments and even worse, multi line comments (and #if or #idefs). This will make life really hard.
And, for the closing brackets, and for example Allman style, you will know the needed indentation only after you printed already the "indentation spaces". So you need to work line oriented or use a line buffers, before you print a complete line.
Example:
}
In this one simple line, you will read the '}' character, after you have already printed the spaces. This will always lead to wrong (too far right) indentation.
The logic for only this case would be complicated. Ant then assume statements like
if (x ==5) { y = 3; } } } }
So, unfortunately I cannot give you an easy solution.
A parser would be needed, or I simply recommend any kinde of beautifier or pretty printer
I was just wondering about something that popped into my mind while writing some code.
for (int i = 0; i < num_bits; i++) {
if (bits.at(i) == 0) {
}
else if (bits.at(i) == 1) {
}
}
In this code, bits is a string and num_bits is the length of the string.
In this case, would the program run string.at(i) at both the if and the `else if``, or would it run it once and then store it somewhere and use it at both of the statements? I don't know if the question was clear enough, but thanks for any answer.
Think about it. How would the engine know that every call to that function would produce the same result?
It wil run the function whenever you call it, so for this example 2 times. You can declare it at the top of the for loop or use a foreach if you need to do more heavy operations.
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).
I'm iterating through an array of chars to do some manipulation. I want to "skip" an iteration if there are two adjacent characters that are the same.
e.g. x112abbca
skip----------^
I have some code but it's not elegant and was wondering if anyone can think of a better way? I have a few case's in the switch statement and would be happy if I didn't have to use an if statement inside the switch.
switch(ent->d_name[i])
{
if(i > 0 && ent->d_name[i] == ent->d_name[i-1])
continue;
case ' ' :
...//code omited
case '-' :
...
}
By the way, an instructor once told me "avoid continues unless much code is required to replace them". Does anyone second that? (Actually he said the same about breaks)
Put the if outside the switch.
While I don't have anything against using continue and break, you can certainly bypass them this time without much code at all: simply revert the condition and put the whole switch statement within the if-block.
Answering the rectified question: what's clean depends on many factors. How long is this list of characters to consider: should you iterate over them yourself, or perhaps use a utility function from <algorithm>? In any case, if you are referring to the same character multiple times, perhaps you ought to give it an alias:
std::string interesting_chars("-_;,.abc");
// ...
for (i...) {
char cur = abc->def[i];
if (cur != prev || interesting_chars.find(cur) == std::string::npos)
switch (current) // ...
char chr = '\0';
char *cur = &ent->d_name[0];
while (*cur != '\0') {
if (chr != *cur) {
switch(...) {
}
}
chr = *cur++;
}
If you can clobber the content of the array you are analyzing, you can preprocess it with std::unique():
ent->erase(std::unique(ent->d_name.begin(), ent->d_name.end()), ent.end());
This should replace all sequences of identical characters by a single copy and shorten the string appropriately. If you can't clobber the string itself, you can create a copy with character sequences of just one string:
std::string tmp;
std::unique_copy(ent->d_name.begin(), ent->d_name.end(), std::back_inserter(tmp));
In case you are using C-strings: use std::string instead. If you insist in using C-strings and don't want to play with std::unique() a nicer approach than yours is to use a previous character, initialized to 0 (this can't be part of a C-string, after all):
char previous(0);
for (size_t i(0); ent->d_name[i]; ++i) {
if (ent->d_name[i] != previous) {
switch (previous = ent->d_name[i]) {
...
}
}
}
I hope I understand what you are trying to do, anyway this will find matching pairs and skip over a match.
char c_anotherValue[] = "Hello World!";
int i_len = strlen(c_anotherValue);
for(int i = 0; i < i_len-1;i++)
{
if(c_anotherValue[i] == c_anotherValue[i+1])
{
printf("%c%c",c_anotherValue[i],c_anotherValue[i+1]);
i++;//this will force the loop to skip
}
}
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;
}
}