Exception Handling Question:

Hello,

I'm practicing Exception Handling, which is fairly new to me in C++. I want to be able to properly handle a 0-length array without using exception-handling.

This is my code using exception handling:
1
2
3
4
5
6
7
8

int min(int arr[], int n) {
	if (n == 0) throw string("zero-length array passed to min");
	int result = arr[0];
	for (int i = 1; i < n; i++)
		if (arr[i] < result) result = arr[i];
	return result;
}


This is what I am having trouble with (my code without using exception handling):

1
2
3
4
5
6
7
8
9
 23 int min(int arr[], int n) {
 24         if (n == 0) {
 25         string("zero-length array passed to min");
 26 }
 27         int result = arr[0];
 28         for (int i = 1; i < n; i++);
 29                  if (arr[i] < result) result = arr[i]; 
 30                 return result;
 31 }


I want to note that this is a seperate file from the main() file. I'm trying to manage my program using seperate compilation.

As I compile this file though I am getting errors these errors:
array_utils.cpp: In function 'int min(int*, int)':
array_utils.cpp:29:12: error: name lookup of 'i' changed for ISO 'for' scoping [-fpermissive]
array_utils.cpp:29:12: note: (if you use '-fpermissive' G++ will accept your code)


'tis why I need some advice. Thank you for taking the time!

You have put a semicolon at the end of line 28 so line 29 will not be part of the for loop.
!! Thank you
Topic archived. No new replies allowed.