The following code compiles, but I was just wondering whether it was safe or an unsound practice
to ignore the additional if (randvar >=3) //{do stuff} line and just continue the code, (particularly if the continued code is exactly what the randvar result would want to do if it was 3 or more. )
Thanks for any clarification on this.( Not sure of the correct terminology above).
Code:#include <iostream> #include <ctime> using namespace std; int otherFunc (int randvar) { // do whatever return 0; } int main () { srand (time (NULL)); int randvar = (rand()%10+1); if (randvar <= 2) { otherFunc (randvar);} cout<<" do other stuff ignoring if (randvar >=3) {// }" <<endl; cin.ignore().get(); return 0; }
I don't think I understand your question.
Sorry.
I guess I mean the next line of code after if (randvar <= 2) { otherFunc (randvar);}
should be if (randvar >=3) { do something else);}
I know if I omit if (randvar >=3) { do something else}
and just continue the code it compiles, but what I was just wondering was
whether this was acceptable or not?
I'm not sure if I undertand correctly your question...
The code is syntactically correct with or without the "if (randvar >= 3)". Another question is what do you really want to do. If you do not add the condition, then both statements (the otherFunc call and the cout) will be executed when randvar <= 2, and only the last one otherwise. In the other hand, if the condition is added, only one of the statements will be executend, depending on the value of randvar. If this is the case, I think the best way would be:
Code:#include <iostream> #include <ctime> using namespace std; int otherFunc(int randvar) { // do whatever return 0; } int main() { srand(time(NULL)); int randvar = (rand() % 10 + 1); if (randvar <= 2) { otherFunc(randvar); } else // or "if (randvar >= 3)" if you like { cout<<" do other stuff ignoring if (randvar >=3) {// }" <<endl; } cin.ignore().get(); return 0; }
Thanks dbug thats exactly what I wanted to know. Whether either method was syntactically acceptable.
Trying to awkwardly express such a query made googling it impossible!
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks