Function and pointer questions

I have two questions please about the code below.
1. Why is the function declared at the beginning and then structured later after main, why not structure it at the beginning when it was declared? I saw this a few times.

2. Why does the function return max instead of *max?

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
  #include<iostream>
#include<conio.h>

using namespace std;

int *findMax(int arr[], int n);


int main() 
{
	int n, i, *p;
	cout << "Enter number of data values";
	cin >> n;
	int arr[n];
	for (i = 0; i<n; i++) 
	{
		cout << "Enter value"<<i+1<<":";
		cin >> arr[i];
	}

	p = findMax(arr, n);
	cout << "The max value is:" << *p;
	getch();
	return 0;
}

int *findMax(int data[], int n) 
{
	int *max = data;
	int i;
	for (i = 1; i<n; i++) 
	{
		if (*max<*(max + i)) *max = *(max + i);
	}
	return max;
}
1. You could do it that way if you wanted to. Doing it the way you have it now shows you the distinction between DECLARING a function (line 6), and DEFINING a function (lines 27-36). When that function is called in main, the compiler makes sure that the function has been declared. Later, the linker will make sure there is a definition for the function.

2. findMax is specified as a function that returns a "pointer to integer". That is the function's "return type". "max" is declared of type "pointer to integer". See how the type of "max" and the "return type" are the same? Contrast with the type of "*max". Putting the asterisk there indicates that we want to dereference the pointer. That basically means "get the thing that's being pointed to", which in this case is an int. The function doesn't return an int, it returns a pointer to int. Therefore, the dereference is unnecessary.
Thank you very much!
Topic archived. No new replies allowed.