Help with function references


#1

Hi,
I’m learning C++ and I’m in a bit of a rut here. Could anyone help me out?

First of all I can’t fully grasp what is going on in this section of code. The code is to find the biggest element in an array.

#include <iostream.h>

main()
{
	int biggest( int item_array[], int n_elements );

	int item_array[5] = { 1, 2, 35, 3, 4 }; //An array

	cout << "The biggest element is " << biggest(item_array, 5) << "
";

	return(0);
}

int &biggest( int array[], int n_elements )
{
	int index; //Current index
	int biggest; //Index of the biggest element in the array

	//Assume the first is the biggest
	biggest = 0;
	for( index = 1; index < n_elements; ++index )
	{
		if(array[biggest] < array[index])
		biggest = index;
	}

	return(array[biggest]);
}

Is the variable biggest [ int biggest; //Index of the biggest element in the array ] a reference to the function biggest [ int

&biggest( int array[], int n_elements ) ]?

Starting with the function we make the function biggest a reference. We then declare the parameters array[] and n_elements.

Maybe my problem is that I don’t fully understand the references. How exactly does the reference work?

We then create the variables index and biggest - that I understand.

We then state that

	biggest = 0; 

being the biggest element in the array currently known.

Then we create the loop, stating that while index = 1 and index < number of elements in the array the index must be incremented.

Then to determine whether biggest is still the largest element in the array, or not, we use an if statement:

	if(array[biggest] < array[index])

If it is smaller, then we must change it’s value accordinly:

	biggest = index;

We then return the value of our function. 


return(array[biggest]);


Then we want to print out the biggest element in the array, so we define the function prototype:


int biggest( int item_array[], n_elements );


We then define the array, item_array:


int item_array[5] = { 1, 2, 35, 3, 4 };


Then we print the biggest element in the array:


cout << "The biggest element is " << biggest(item_array, 5) << "

";



The problem is that when I run the program (after compilation) it returns the result:

	The biggest element is 37879624

Shouldn't it be 35?

I would really appreciate any help. Cheers

#2

The code will work like this. Have a look at it and then feel free to ask any open questions.
But please look exactly at the differences and think about them.

#include <iostream>

int biggest(int array[], int n_elements) {
	int biggest = 0;
	for(int index = 1; index < n_elements; index++)	{
		if(array[biggest] < array[index])
			biggest = index;
	}
	return array[biggest];
}

int main() {
	int item_array[5] = { 1, 2, 35, 3, 4 };
	std::cout << "The biggest element is " << biggest(item_array, 5) << std::endl;
	return 0;
}

#3

Hey schmu_20mol!
Thanks for your help! Very much appreciated. If you dont mind I’ll ask a couple of questions.

I edited the code to see if it would work (not that your code didn’t work), just that I’m very new to C++ (only been at it nearly 2 weeks now) and I changed the code to what i’m comfortable with. Anyway here are my questions:

 

int biggest(int array[], int n_elements) 
{
	int index;
	int biggest = 0;
	for(index = 1; index < n_elements; index++)	
	{
		if(array[biggest] < array[index])
			biggest = index;
	}
	return(array[biggest]);
}


When you define the function, don’t you have to create references? Meaning that, what would be the difference in making the function a reference, and how exactly does it call on a reference? I tried the code with the function as a reference and not as a reference, and both work.

Sorry if i sound so blatantly ignorant, but could anyone tell me what is a reference?

As far as I know, a reference is a way of refering to a certain variable, so when that variable changes it affects the other? What I mean is that, shouldn’t int array[] be a reference to another array variable?

Looking at the main function:



int main() 
{
	int item_array[5] = { 1, 2, 35, 3, 4 };
	cout << "The biggest element is " << biggest(item_array, 5) << "
";
	return(0);
}


What really confuses me is that how you can put item_array[5] = { 1, 2, 35, 3, 4 }; inside the biggest function without defining a reference. Like so:

		biggest(item_array, 5)		

I might as well provide the following piece of code to illustrate my frustration:

		

#include <iostream.h>

int inc_counter( int counter )
{
	++counter;
}

main()
{
	int a_count = 0;
	
	inc_counter(a_count);
	cout << a_count << "
";
	return(0);
}


The above code will not work unless you make the counter parameter a reference, like so:



int inc_counter( int &counter ) //Make parameter counter a reference


Also I’m really confused that you dont declare the function prototype in the main function.

		int biggest( int array[], int n_elements ); //Function prototype of function biggest 		

Shouldn’t that be essential? Anyway, thanks very much indeed for your help. I hope you can help me out again?

Cheers!

PS [q] Reason: overseen std::endl/"
" [/q]

I just saw this on the end of your message. The code still works, with or without the std::end1…


#4

#1 -> when you declare a variable then give it a value (take this as a rule of thumb) and declare the variable at best at the moment you need it (in the for-loop)
#2 -> those parenthesis aren’t needed, try not to oversaturate your statements/epressions with unnecessary stuff

References are used to provide alternative names for variables, so they have to refer to something when initialized. Think of a reference as a constant pointer. Operations applied to the reference affect the referred variable (or object). Like,


int i = 20;
int &r = i;

r++; // -> increments i

#1 -> iostream is part of the STL so it doesn’t need the .h and the “” it’s simply
#2 -> ++i increments i before the statement/expression(pre), i++ increments i after the statement/expression(post); you should have a close look on what you really need
#3 -> a_count is still 0, you haven’t put the result of your function calling in that line; it should read

 
std::cout << inc_counter(a_count) << std::endl;

or


int blah = inc_counter(a_count)
std::cout << blah << std::endl;

with the first version as the one to go.

#4 -> check out #3 of the above example

Generally don’t forget to use your namespace either with

 using namespace std;

or

 std::cout ....

No need to declare this one. Your source code will get parsed from the top to the bottom, when the main function is reached by the parser the ‘biggest’-function will already be known. It is indeed unnecessary bad behaviour to declare all those in the main. You do that when you have some circular references going on.

This is a matter of style as in: std::endl will definately flush your output stream.

I hope this helps. If you need to know more or if I have overseen something then just post it.

And btw do yourself a favour and get ‘The C++ programming language’ by Bjarne Stroustrup


#5

Hey schmu!
Thanks for your reply!
Ok, good points about declaring and naming the variable only when you need it, and leaving out the parentheses.

Thanks for making those references seem clearer to me! Very much appreciated!

I didn’t know that you could put the increment operator both in front and behind the variable! Thanks for pointing that out. So if you had a loop you could increment the variable before starting the loop, like so:



	int variable;
	
	++variable; //Increment the variable before the statement/expression

	loop;


Or have the loop increment the variable, like so:



	int variable;

	loop

	variable++; //Increment after the statement/expression


Is that correct?

Ok, I see about the function prototype. So obviously, I don’t need to put it in into main.

Thanks very much for your help. I really appreciate it.

Yeah, I will try get that book. I picked up Steve Oualline’s book, Practical C++ Programming at a second-hand bookstore. But hopefully I can get my hands on the other book :wink:

Thanks again dude!

Cheers!


#6

The thing with the increment is that when you have a prefix (++i) it is incremented before the statement/expression is evaluated, and if you have a postfix (i++) it is incremented after the evaluation of the statement/expression.
At least that’s like I know it :wink:


#7

Hey thanks man! Sure you helped clear me up on a few things! Cheers!


#8

I honestly don’t want to sound like a smart a** but those principles are essential and can be found in many languages you might encouter. So keep them in mind and you’re helping yourself a lot. :thumbsup:


#9

hey dude!
thats totally cool! i understand. yeah, should help my MEL! laters! :slight_smile:


#10

On the increment thing (no offense meant, schmu_20mol, but, while what you said was right, it maybe didn’t come across as clearly as it could…)

If we look at the following code:


 int a = 0;
 int b;
 
 a++; // set a to 1
 ++a; // set a to 2
 
 b = a++; // set b to a(2), a to 3
 b = ++a; // set a to 4, b to a(4)
 

So where the ++ comes only matters when you are using the a++/++a as part of a statement - if it’s a line on it’s own, then it makes no difference at all…

Oh, and while the Straustrup book is a fantastic reference book, if you’ve only been learning C++ for a couple of weeks, be careful with it… you could get very confused with it, as it goes into a lot of depth…


#11

none taken…to be honest - your explanation is indeed better :wink:


#12

In the first code block posted, the first line with “int biggest…” is not a variable, it’s a prototype for the biggest() function.

It’s not common for function prototypes to exist within other functions, and I’m not even sure it’s 100% legal C. The vast majority of the time, prototypes belong at top level (or within a class {} or namespace {} block).


#13

well I don’t want to stress you but you do know what RTFT means?


#14

Rough Terrain Forklift Truck…

What’s that got to do with programming? :wink:


#15

awww… spoiled the pun
:smiley:


#16

This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.