Exit early (abort) and max # of tests allowed.

This is a discussion on Exit early (abort) and max # of tests allowed. within the C++ Programming forums, part of the General Programming Boards category; Ok, I have two more questions. Is there a way to about the current evaluation, say, if you want the ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    26

    Exit early (abort) and max # of tests allowed.

    Ok, I have two more questions.


    Is there a way to about the current evaluation, say, if you want the program to abruptly end for whatever reason..

    and

    How many if's &&'s and ||'s can you do?

    I mean, is this legal (code below) or is there some elegant way of asking for 3 different logical operations?



    Code:
    if (num > 0 && num < 100 && num != 50)
        do something.....
    else
       do something else....

  2. #2
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    it is legal

    what is more elegant when to ask 3 logical operations combined with logical Or/AND?

    Is there a way to about the current evaluation
    What do you mean?

    If you asking will the program continue to evaluate the logical expression if the result is already determined based on the left part - then no, evaluation is stopped as soon as the result is known

    this gives a possibility to write something like
    Code:
    if(p && p->str)
       puts(p->str);
    and even if the p is NULL this code will not cause the crash
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    How many if's &&'s and ||'s can you do?
    More than you ever need. I think there is a statement in the C standard that says the compiler must allow 127 or something along those lines, but that's not to say that modern compilers won't do more than that.

    I just compiled this [snipped to keep it short]
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define SIZE 1000
    #define LIMIT 60
    
    int main()
    {
      int x[SIZE];
      int i;
      for(i = 0; i < SIZE; i++)
        {
          x[i] = rand();
        }
    
      if (
          x[0] > LIMIT && 
          x[1] > LIMIT &&
          x[2] > LIMIT &&
          x[3] > LIMIT &&
          x[4] > LIMIT &&
          x[5] > LIMIT &&
          x[6] > LIMIT &&
          x[7] > LIMIT &&
          x[8] > LIMIT &&
          x[9] > LIMIT &&
          x[10] > LIMIT &&
    <....>
          x[48] > LIMIT &&
          x[49] > LIMIT
          )
        {
          printf("All numbers above LIMIT\n");
        }
      else
        {
          printf("Some numbers under LIMIT\n");
        }
          
      return 0;
    }
    So that is 50 && conditions in one expression. If your actual code reaches 50 conditionals in one statement, you probably should rethink your solution in some way.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Registered User
    Join Date
    Jul 2008
    Posts
    26

    What about combining them

    Quote Originally Posted by matsp View Post
    Code:
    How many if's &&'s and ||'s can you do?
    More than you ever need. I think there is a statement in the C standard that says the compiler must allow 127 or something along those lines, but that's not to say that modern compilers won't do more than that.

    I just compiled this [snipped to keep it short]
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define SIZE 1000
    #define LIMIT 60
    
    int main()
    {
      int x[SIZE];
      int i;
      for(i = 0; i < SIZE; i++)
        {
          x[i] = rand();
        }
    
      if (
          x[0] > LIMIT && 
          x[1] > LIMIT &&
          x[2] > LIMIT &&
          x[3] > LIMIT &&
          x[4] > LIMIT &&
          x[5] > LIMIT &&
          x[6] > LIMIT &&
          x[7] > LIMIT &&
          x[8] > LIMIT &&
          x[9] > LIMIT &&
          x[10] > LIMIT &&
    <....>
          x[48] > LIMIT &&
          x[49] > LIMIT
          )
        {
          printf("All numbers above LIMIT\n");
        }
      else
        {
          printf("Some numbers under LIMIT\n");
        }
          
      return 0;
    }
    So that is 50 && conditions in one expression. If your actual code reaches 50 conditionals in one statement, you probably should rethink your solution in some way.

    --
    Mats

    What about combining the statements..

    like:

    if (something > somethingelse && something > anothing thing && something != somethingdifferent || something < someotherdifferentthing)

    What is allowed for something like that? In Autolisp you would use the COND function, which evaluates several different situations like:

    Code:
    cond ((x > y) (setq a 1)) ;SETQ is equal to the A = B; It just "sets equal" 'A' to 'B'. 
            ((x < v) (setq a 2))
            ((a = 1) (alert "X is Greater than Y!"))
            ((a = 2) (alert "X is Less than V!"))
    .... and keep going (lisp is used with parenthesis and different syntax obviously)

    is there a way to do something like this in C / C++? I know about the switch command, but that requires an integer (or single character) to determine a condition.. I would like to just switch a condition depending on the outcome of the previous (or just one) original condition. (Or maybe you WOULD make use of the switch command?) I don't know how it's normally done in C/C++.

    Thanks.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    I guess you could use something like this.
    Code:
    int a;
    
    if(x > y) a = 1;
    else a = 2;
    
    switch(a) {
    case 1:
        std:cout << "x > y";
        break;
    case 2:
        std:cout << "x <= y";
        break;
    }
    Of course, I don't really see the point. It's basically the same thing as this:
    Code:
    if(x > y) std:cout << "x > y";
    else std:cout << "x <= y";
    [edit] Thinking about it, I think what you're looking for is the "else" statement. An else statement can follow any if. If the if's condition is false, the else clause is executed. You can combine them, too.

    Code:
    if(x > y) this();
    else if(x < y) that();
    else {  // x == y
        equal();
    }
    http://www.cprogramming.com/tutorial/lesson2.html [/edit]
    Last edited by dwks; 08-15-2008 at 04:37 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Registered User
    Join Date
    Jul 2008
    Posts
    26

    Exiting evaluation..

    Quote Originally Posted by vart View Post
    it is legal

    what is more elegant when to ask 3 logical operations combined with logical Or/AND?


    What do you mean?

    If you asking will the program continue to evaluate the logical expression if the result is already determined based on the left part - then no, evaluation is stopped as soon as the result is known

    this gives a possibility to write something like
    Code:
    if(p && p->str)
       puts(p->str);
    and even if the p is NULL this code will not cause the crash

    No, I mean COMPLETELY exiting. Like, if the very first thing is not true, then just exit.. or if you get a few things into it, and something evaluates to false, then just exit.. otherwise you have to figure out how to write the code AROUND these statements when you already know that you don't need to go any further. It is the equivilent of the basic GOTO [END] statement.

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    Well, if you're in a function, you can use the return statement. For example, from main, you can just use "return 1;" to exit the function. (1 is typically used to indicate failure, while 0 means success.)

    You can also use the exit() function from <stdlib.h>. This exits the program, even from different functions.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    Registered User
    Join Date
    Jul 2008
    Posts
    26

    switch

    Quote Originally Posted by dwks View Post
    I guess you could use something like this.
    Code:
    int a;
    
    if(x > y) a = 1;
    else a = 2;
    
    switch(a) {
    case 1:
        std:cout << "x > y";
        break;
    case 2:
        std:cout << "x <= y";
        break;
    }
    Of course, I don't really see the point. It's basically the same thing as this:
    Code:
    if(x > y) std:cout << "x > y";
    else std:cout << "x <= y";
    [edit] Thinking about it, I think what you're looking for is the "else" statement. An else statement can follow any if. If the if's condition is false, the else clause is executed. You can combine them, too.

    Code:
    if(x > y) this();
    else if(x < y) that();
    else {  // x == y
        equal();
    }
    http://www.cprogramming.com/tutorial/lesson2.html [/edit]

    Here, I'll just post what I have so far, with the problem I have commented out.. maybe that will be easier for to explain.

    Code:
    #include <cstdlib>
    #include <iostream>
    #include <iomanip>
    
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
     		
     		float time, minutes, remainder, rate, total;
     		
     		
     		cout << "Enter start time: " << endl;
     		cin >> setprecision(2) >> time;
     		remainder = time - static_cast<int>(time);
     		if (time > 0 && time < 23.6) // <-------------- need to make sure time is > 0 < 24
     		if (remainder < 0.6)
     		
     		
     		
     		{
    		 	 cout << "enter minutes: ";
    		 	 cin >> minutes;
    			 if (minutes > 0 && minutes < 601)
    			     cout << endl << "Thank you. " << endl;
    			 else
    			     cout << "Number must be between 1 and 600";
    			 if (time > 0 && time < 7.00)
    			 			 rate = 0.12;
    	 			 else if (time > 6.59 && time <= 19.00)
    	 			  	 rate = 0.55;
    	  	   else if (time > 19.00 && time < 24.00)
    		  	  	 rate = 0.35;
    		  	  	 total = minutes * rate;
    		  	  	 
    		  	  	 cout << setprecision(2) << fixed << showpoint << endl; 
    						 cout << "Your total is: $" << total << endl;
    			 }
    			 else 
    			 cout << "Invalid number, try again";
    
     		cout << endl;
     		cout << endl;
     		cout << endl;
     		cout << endl;
     		cout << endl;
     		cout << endl;
     		cout << endl;
     		cout << endl;
     		cout << endl;
     		cout << endl;
     		
     		
        system("PAUSE");
        return EXIT_SUCCESS;
    }

  9. #9
    Registered User
    Join Date
    Jan 2008
    Posts
    287
    How the heck did you ever survive Lisp indenting like that?

  10. #10
    Registered User
    Join Date
    Jul 2008
    Posts
    26

    Thanks

    Quote Originally Posted by arpsmack View Post
    How the heck did you ever survive Lisp indenting like that?
    Yes, I realize it looks like crap. It looked better before I pasted it into here. It changed the indentation quite a bit.

  11. #11
    Registered User
    Join Date
    Jan 2008
    Posts
    287
    Sorry about that mostly useless post, but you really should make use of the preview feature to make sure you aren't posting terrible looking code. It REALLY helps people that are trying to lend you a hand.

    To be a little more useful, do you think you could post a brief description of what you want your program to do so that we could compare it to what you wrote, and then point out the part that needs changing?

    For example, here's my description for a number guessing game:
    Code:
    generate a random number (the secret)
    
    1: ask user for a number (the input)
    
    if the input = the secret
       print "You win"
       exit
    
    else if the input > the secret
       print "Too high"
       ask user for another number (goto 1)
    
    else
       print "Too low"
       ask user for another number (goto 1)
    Don't feel like you have to adhere to this format. Just give me a better idea of what you want your program to do.

  12. #12
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,183
    hmm

    Take a look at assert()?

    *edit*
    perhaps something like
    Code:
    bool test_exit(bool x) {
         assert(x);
         if (!x) { /* can only happen if assert is turned off by NDEBUG */
              std::err << "test_exit failed." << std::endl;
              exit(1);
         }
         return true;
    }
    */edit*
    Last edited by cyberfish; 08-17-2008 at 10:51 AM.

  13. #13
    Registered User
    Join Date
    Jul 2008
    Posts
    26

    It's all good

    Quote Originally Posted by arpsmack View Post
    Sorry about that mostly useless post, but you really should make use of the preview feature to make sure you aren't posting terrible looking code. It REALLY helps people that are trying to lend you a hand.

    To be a little more useful, do you think you could post a brief description of what you want your program to do so that we could compare it to what you wrote, and then point out the part that needs changing?

    For example, here's my description for a number guessing game:
    Code:
    generate a random number (the secret)
    
    1: ask user for a number (the input)
    
    if the input = the secret
       print "You win"
       exit
    
    else if the input > the secret
       print "Too high"
       ask user for another number (goto 1)
    
    else
       print "Too low"
       ask user for another number (goto 1)
    Don't feel like you have to adhere to this format. Just give me a better idea of what you want your program to do.

    well, I think I got it working.. just had to add a couple more things, switch some things around and it worked fine. usually I figure it out about 10 minutes after I post a question for help!

    I didn't realize there were so many dedicated individuals willing to help beginners like me on here! Maybe I should save my questions for something that ISN'T just a frustrating homework question! Thanks. !

  14. #14
    Registered User
    Join Date
    Jul 2008
    Posts
    26

    assert

    Quote Originally Posted by cyberfish View Post
    hmm

    Take a look at assert()?

    *edit*
    perhaps something like
    Code:
    bool test_exit(bool x) {
         assert(x);
         if (!x) { /* can only happen if assert is turned off by NDEBUG */
              std::err << "test_exit failed." << std::endl;
              exit(1);
         }
         return true;
    }
    */edit*

    I'll look into that, thanks.

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Zzaacchh View Post
    Yes, I realize it looks like crap. It looked better before I pasted it into here. It changed the indentation quite a bit.
    My guess would be that you have a mixture of tabs and spaces. Tabs expand to 4 or 8 [1] units wide depending on the system, the settings, etc. Spaces are always 1 unit wide. If you have a mixture, and the displaying system is using a different width of tabs than your system [which is highly probable since many editors use tabwidth=4, and most other things (console window, Web Browsers, etc) use tabwidth=8].

    Many editors have an option to change tabs into spaces.

    Also, my recommendation on assert() would be that you only ever test things that MUST NOT BE WRONG. For example, you may expect a FILE pointer to be non-NULL in a function:
    Code:
    void func(FILE *f)
    {
       assert(f != NULL);
       ... 
    }
    But you don't use assert to handle user-input errors [for example]:
    Code:
    int main()
    {
        char fname[1000];
        FILE *f;
        ... // code asks user for filename somehow. 
        f = fopen(fname, "r");
        assert(f != NULL);
    ...
    The assert here is bad, because it will not tell the user what they did wrong [give the wrong filename].

    [1] These are the two most common variants - there are others. And technically, tabs in the middle of text expand to the next tab boundary, but we are talking indentation here, so it normally starts at position 0 too.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21