foreach loop help C++ CLR

Hello, how this loop not stop immediatelly but after return i see next 5 results?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
void SearchTree(String^ path)
{
	static bool found;
	String^ dirName;
zaciatok:
	if (found)
	{
		return;
	}
	try
	{
		for each (String^ dirs in Directory::GetDirectories(path))
		{
			try
			{
				for each (String^ files in Directory::GetFiles(dirs))
				{
					FileInfo^ file = gcnew FileInfo(files);
					Console::WriteLine(file->Name);
					if (file->Name->Contains("hl2.exe"))
					{
						found = true;
						Console::WriteLine("Found");
						goto zaciatok;
					}
				}
			}
			catch (Exception^ ex)
			{

			}
			SearchTree(dirs);
		}
	}
	catch (Exception^ ex)
	{

	}
}


Here is output: http://prntscr.com/bg03kn

Thanks :)
Why bother with your found variable anyway? Just make the return statement after you ConsoleWrite and don't worry about the goto statement or the bool.

New code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void SearchTree(String^ path) {
	String^ dirName;
	try {
		for each (String^ dirs in Directory::GetDirectories(path)) {
			try {
				for each (String^ files in Directory::GetFiles(dirs)) {
					FileInfo^ file = gcnew FileInfo(files);
					Console::WriteLine(file->Name);
					if (file->Name->Contains("hl2.exe")) {
						Console::WriteLine("Found");
                                                return;
					}
				}
			}
			catch (Exception^ ex) {}
			SearchTree(dirs);
		}
	}
	catch (Exception^ ex) {}
}
Last edited on
Hello, recursion. After found is true in one invocation of searchTree, you still have to finish out previous calls in the recursive chain, which have no way of knowing you found what you were looking for since found is never checked aside from the initial entry into searchTree.

Lousy function design. Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
bool SearchTree(String^ path)
{
    try
    {
        for each (String^ dirs in Directory::GetDirectories(path))
        {
            try
            {
                for each (String^ files in Directory::GetFiles(dirs))
                {
                    FileInfo^ file = gcnew FileInfo(files);
                    Console::WriteLine(file->Name);
                    if (file->Name->Contains("hl2.exe"))
                    {
                        Console::WriteLine("Found");
                        return true;
                    }
                }
            }
            catch (Exception^ ex){ }
			
            if (SearchTree(dirs)) return true ;
        }
    }
    catch (Exception^ ex) { }
    return false;
}
Thanks guys, it works both, now im using cire's code. I try with return before, but dont know why, program still continue. Now it works, thanks again.
Topic archived. No new replies allowed.