Chimdi2000
Chimdi2000

Reputation: 366

can an if statement ever be used to check a while loop?

some hacker folks are debating over this issue and I felt like getting the right answer here

If (condition_c){

While (condition_c){
//code here
}
}

Is there any case or situation that this can be done? If yes, give a situation that justify ur answer.

Upvotes: 0

Views: 57

Answers (2)

mmachenry
mmachenry

Reputation: 1962

This is possible in all languages that support IF and WHILE since you're just simply composing the two constructs. There are limited situations in which this would actually be meaningful. Assuming you don't have any other code between your IF and your WHILE (just like you don't in your example) there's really only one reason this would be meaningful and that's if you have side effects in your condition. Consider the following snippet of Perl code.

if ($line = <STDIN>) {
    while ($line = <STDIN>) {
        print $line;
    }
}

In this program, the IF is meaningful because the state of my input buffer is different the second time I compare it. This snippet of code could be useful if I wanted to, for example, print out all the lines of a comma-separated value file but drop the header, which is the first line.

Now you might say to me that this could be written better by not putting the first read inside the IF but perhaps I want to tack and ELSE onto that IF. There's always more than one way to write stuff so keep that in mind.

So in conclusion this code is meaningfully different in the event that the condition has side effects. Other examples could be something like "$x-- == 0" or "f(x)" where f has some side effect. If it's just a plain-old boolean value, then no.

Upvotes: 2

Marcin
Marcin

Reputation: 49846

This is almost certainly possible in the majority of programming languages that support such constructs. It is unlikely to be useful in any of them.

Upvotes: 0

Related Questions