# Silly question understanding a simple function

• 11-02-2010
t4yl0r
Silly question understanding a simple function
Hello, all.
I have this simple function in my book that I've utilized to search through a linked list. However HOW it works is really stumping me, I would be very grateful if someone can elaborate as to why this function does what it does:

Code:

{
if (here == NULL)
{
return false;
}
else
{
while (here->data != target && here->link != NULL)

if (here->data == target)
return true;
else
return false;
}
}

First of all I don't understand why there are no brackets after while and until the end of the funtion or in hte second if/else statement, but I can only come to the assumption that this is legal since it works.
In the scenario where here->data == target, how the heck would it return true? Is the subsequent if statement OUTSIDE of the loop? If the if/else statement is outside of the loop, how can it decide for each here->data whether it is true or not.

I'm really confused, and kinda noobish :(
Sincerely,
T4yl0r
• 11-02-2010
Daved
When you don't have brackets with a while, if, else, etc, then only one statement is part of that loop or block. So
Code:

while (here->data != target && here->link != NULL)

is the same as
Code:

while (here->data != target && here->link != NULL)
{
}

The same is true for the if and the else. Here is the same code with brackets added and indentation fixed to make it more readable:
Code:

{
if (here == NULL)
{
return false;
}
else
{
while (here->data != target && here->link != NULL)
{
}

if (here->data == target)
{
return true;
}
else
{
return false;
}
}
}

• 11-02-2010
t4yl0r
Daved, thank you for that explanation it really makes sense to me now!
Correct me if I'm wrong but what this function is it reaches the while loop and iterates until
here->data == target. In that case it breaks the while loop, go to the if statement, returns TRUE.

On the other hand, if it reaches the end of the linked list (here->link == NULL) it breaks
from the whole loop, moves on to the if/else statement goes to ELSE and returns false.

I seriously could not read that without the brackets, you are all the best =)

Sincerely,
T4yl0r
• 11-02-2010
Daved
>> Correct me if I'm wrong
No correction. You're exactly right. Glad I could help.