# Pointers & Functions in C++

This topic is 4288 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey, I'm learning C++ and having two problems so far. I'm going along with the 5th edition of C++ for Dummies, which I regret getting because I've never liked the for dummies series before. Right now, I'm at where their talking about pointers. I havn't even bothered to remember how to use them, but are they really important for a beginner? Do you just use them for performance optimization? Is it usually a hard concept to grasp for most? My next problem, is with functions. I read through it's chapter, it appeared before pointers, and I don't understand the argument or return part of the function. I don't get what you put in the argument first of all, and second of all, I don't understand the whole functions returning a value or not, hence the
void/int/char/etc FUNCTIONNAME (argument)


What defines a value to be returned? I'm thinking if you put
cout "Blah blah blah";


Then that'll be the returned value, a string. But it seems like it doesn't have to, but that would mean the function litterally does nothing. I'm use to Python and Blitz3D, where you put the function name, and the variables in the parenthesis, and then put in the code for what the function does.

##### Share on other sites
I'll leave the pointers for someone else to answer, because I'm still a newb with those too :P But the functions isn't too hard.

Basically, in C/C++ you create a function by specifying it's return type, it's name and it's arguments. So it would look like:

type MyFunctionName ( any arguments ) { }

If you don't want the function to return anything, the type should be 'void', thus:

void MyFunctionName ( any arguments ) { }

If you dó want your function to return something, you should specify the type as the type of the value your function is going to return. This looks like:

//sample function that returns an integerint MyFunctionName ( int arg1 ){    return arg1;}

As you can see, if your 'type' isn't void, your function should always return something with the return statement. The value it returns should be of the same type as you declared the function with.

One last issue, if you don't want your function to take arguments, you use 'void' between the brackets, like:

int MyFunction ( void ) {    return 10821;}

##### Share on other sites
But what I don't get, is the return or argument part.

What goes into the argument part?

As for the return part, I find it hard to explain what exactly I mean... but like... I don't know. Maybe two simple programs, one returning something and one not would help.

##### Share on other sites
Ok, here's a little program (to be executed in a console)

#include <stdio.h>// A function to multiply two integers and return the result. Because // multiplying two integers always results in an integer, the return type will // be int.// Arguments, we need to pass the two numbers that we want to multiply to // the function.int Multiply ( int number1, int number2 ) {    // Declare a new integer, called answer    int answer;    // execute the multiplication    answer = number1 * number2;    // return the answer    return answer;}// Our main function, this is the function that's called at startup. It returns an integer. int main(){    // here, we will make our call to the Multiply function    int num1 = 5;    int num2 = 6;    int ans;    ans = Multiply ( num1, num2 );    cout << num1 << " times " << num2 << " is " << ans << endl;    // because main() was specified to return an int we just return 0 here    return 0;}

##### Share on other sites
The arguments are the parameters for your function. For example:

{
return a + b;
}

the first int specifies the the function will return an int as type. add is the name of our function. then we get the arguments part. int a, int b means that we have 2 parameters(seperated by a comma as shown in the example). both parameters are of type int. We can use these parameter in out function like variables. now we can use the following code:

this line of code will give x the value 5. because a will be 3 in out function and b will be 2. the function would return 3 + 2 which is 5.

Fyber

##### Share on other sites
Thanks alot, that cleared it all up!

##### Share on other sites
Ooookay, first of all, pointers. Pointers [in c/c++] are the bread and butter of complicated operations, and are absolutely required for anything beyond the more straight forward programming basics. Pointers are a tool [one that from what i understand, are for some odd reason the main road block that stands between most people learning C/C++ and understanding C/C++], and as any tool, can be avoided completely so long as you are willing to avoid attempting the tasks that require thier use. They are a huge part of C/C++/[tons of other langs] though, so if you plan on learning a language that uses pointers, you'll benefit greatly to devoting the time to understanding pointers. Pointers are a bit like math though, in that people seem to fight tooth-and-nail learning them, but if you just give up the fight of trying to work around them, they'll come a lot easier, and they'll seem to have a very natural form. Unfortunately you've got a bit of catching up to do in this sense, since the dummy programming books always seem to crash and burn when it comes to explaining these kinds of topics well, and i happen to know for certain that at least 'learn C for dummies' crashed and burned spectacularly when it came to teaching pointers, though perhaps the c++ version is better. Pointers are kinda the magical tool in c-like languages though, and you can accomplish so much more once you get the idea down pat, than you ever thought you could just by learning them originally.

As far as functions go though, consider the form of the function to be something like this

[Single thing that comes out] Function name ([List of things that go in])

where 'void' simple means 'nothing'.

int Function(int x, int y) {return (x + y);}
would be called like
c = Function(a,b);
where c,a,b are all int's

x and y are seperate values that are initialized with the VALUE of a and b upon the call of the function, added together, and returned [thus nothing actually happens to variables a and b in this function, EVER!!!!! 'call by reference' is just fancy talk for 'pass the address, and operate on that'.. you don't actually change the address, you just change the values that exist at that address] It of course gets more complicated once you start getting into some of the uglier variable types, like deeper levels of pointers [pointers to an array of pointers to pointer pointers?... yuck], but if you understand the basic concept, NOTHING can shake you.

##### Share on other sites
I know you didnt ask how to use pointers, but I just though Id show you how easy it is to use them.

Create an integer

int test;

Create a pointer to an integer

int* ptest;

At this point the ptest pointer is pointing to a random memory address, and can not be used without disastrous results.

Make the pointer point to the integer

ptest = &test;

What happens here is that the address of the test integer is copied into the pointer. The ampersand (&) will make sure we get the address of test rather than the contents.
Note that a pointer is nothing more than a variable big enough to hold any memory address. On a 32 bit system that is 4 bytes.

Now, if we print the ptest pointer cout << ptest << endl;
This will print the contents that the pointer holds, which is the address of test.
The same way cout << test << endl; will print the contents of the test integer.

In order to get to the test integer through our pointer, we need to dereference it with an asterisk
cout << *ptest << endl;

The asterisk make sure that the contents of the ptest pointer is treated as an address to another variable, rather than just a value.

Its not that hard to get used to pointers, the reason people find them "hard to use" is becouse of the nature of the errors you get when you use them wrong.
Bottom line is that if you make a mistake when using a pointer, your compiler will not warn you when you compile the program. Instead your program will most likely crash (and burn) when you run it.
Tracking down pointer errors can also be hard, since the program dont always crash at the line where the miss-use of the pointer is done.

Here is a pretty good online book for C++ basics you might wanna check out

##### Share on other sites
Well, I get how you literally use them, but to use them effectivly, as to actually doing something, I have no idea. What? I make a pointer for every variable? Every double variable? Long variable?

##### Share on other sites
Infact there is quite a few situations where you want to use pointers.

Ill give you a couple:

1.
Every process gets a limited amount of memory from the OS when it is created, the so called stack.
Lets say that the stack size of the process is 10k bytes big.
Now you want to load a image from disk. The problem is that the image has a size of 100k bytes. Obviously there is not enough space on the stack to hold this image.
The infamous way to solve this is to "ask" the OS to allocate more memory to our process. This is done with the new operator in C++, or the malloc function in C.
The thing is that these operators/functions return a pointer to the new memory.
There is no way we can fit this memory in our default stack, so when we want to access this memory, were stuck with this pointer.

2.
Say I need to send a huge data structure as an argument to a function.
C/C++ will always make a copy of every function argument, so making a copy of this huge structure is costly and inefficcient.
A common way around this is to make a pointer to the structure instead, and pass that as the function argument. No matter how big the structure is, the pointer pointing to it is alway just 4 bytes big, and can be copied much more efficient.

3.
A common concept in C/C++ is so called abstract data types (ADT).
An example of an ADT is a list. A list is built up of data structures, where each structure holds a value (for example a phone number), and a pointer to the next structure in the list. There is other types of ADT as well like stacks, trees and queues. They all have the common feature that each structure in the list/stack/tree have to hold one or more pointers to their connected structures.
As you can see, it would be impossible to make ADT's like this without pointers.

Im sure there is a lot of other cases too where pointers is either needed or prefered.
You can be pretty sure that the chapters later in the book will require you to know how to create and use pointers.

##### Share on other sites
Besides dynamic memory allocation(which shouldn't bother you if you use STL, and you should) and faster code(which, as a beginner, doesn't interest you much), pointers provide another very important feature: References to existing objects. C++ already has references as a feature distinct from pointers, but they're not resetable,ie you can't change them in the middle of your program. I've given this example before in these forums: Say you are making an FPS game. You will have a "player" object, and several "enemy" objects. Let's say you have 2 objects of type Enemy named "demon" and "zombie". You want the player to be able to "lock" its target to the demon, and when he shoots, to kill him. Naturally you need a variable to store the current target. What type will the variable be? Will it be type Enemy? No, because a variable of type enemy is a new, distinct object. If you do:

Enemy target;
target=demon;
target.Die();

you will not get the results you expect. "target" is an exact copy of demon, but a completely distinct object. A clone. When you call target.Die(), you don't kill the demon, you kill the object "target". The demon is unaffected. That's what pointers are used for. By doing:

Enemy* target;
target=&demon;//Set target to demon
target->Die();//Kill current target(ie demon)
target=&zombie;//Set target to zombie
target->Die();//Kill current target(ie zombie)

Target now is not a distinct Enemy object, but a pointer to an Enemy object. By using the pointer, you can manipulate whatever object "target" points to at the moment.