Qbasicnews.com

Full Version: what is the command to exit a loop in C?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
:*(
break
Smile
Yes, just looked it up in my C "white book".
Break will exit the innermost do, while or for loop.
*****
Break will also exit "switch" selective structures:

Code:
switch (c)
{
   case 1: puts("One.");
   case 2: puts("Two.");
}

If c equals 1 it will print

Code:
One.
Two.

We need to add the break instruction:

Code:
switch(c)
{
   case 1:
      puts("One.");
      break;
   case 2:
      puts("Two.");
}

You may ask yourself... What's the use of this? Easy. In QB you can do:

Code:
CASE 1,2,3,7: PRINT "one, two, three, or seven"

But you can't do it in C. Instead you write:

Code:
case 1:
case 2:
case 3:
case 7:
   puts("one, two, three, or seven");

IMHO, it is more flexible than QB's approach. Look at this code which gives some info about numbers from 0 to 9:

Code:
case 3:
case 5:
case 7:
   puts("It is prime");
case 2:
   puts("It is even");
   break;
default:
   puts("Not prime.");

The QB translation is trickier:

Code:
CASE 2: PRINT "It is prime.":PRINT "It is even."
CASE 3,5,7: PRINT "It is prime."
CASE ELSE: PRINT "Not prime."

Which looks strange (imagine that you have MORE code than a single PRINT).
Under Turbo-C, there is a GOTO statement. You can jump out loops with it too.
as in

GOTO outofloop? Smile
Quote:Under Turbo-C, there is a GOTO statement. You can jump out loops with it too.

goto is evil.
Do you want the "big - flames - thread" back in da new forum?
Quote:goto is evil.

Nah, goto is cool.
Code:
$ cd /usr/src/linux-2.4
$ grep -r "goto" * | wc -l
14830

setjmp and longjmp are evil.
Pages: 1 2