In simple programs with numerous functions, which do you guys prefer to use:
1) References to variables (&)
2) Pointers (*)
Just wondering as I read somewhere that you should use references wherever possible.
In simple programs with numerous functions, which do you guys prefer to use:
1) References to variables (&)
2) Pointers (*)
Just wondering as I read somewhere that you should use references wherever possible.
>which do you guys prefer to use
If there's a chance that a parameter or return value can be invalid, use a pointer so that you can test for NULL. Otherwise use a reference. Just follow that simple guideline and you shouldn't have problems.
My best code is written with the delete key.
>>or return value can be invalid, use a pointer so that you can test for NULL.
Or, if you feel like copying Microsoft, you can add an extra parameter that's a reference to a boolean variable, to indicate whether the return value is valid or not. And if you want to make that extra parameter optional, you could change the boolean reference to a pointer instead, which brings you back to the beginning again
I like references mostly, because dereferencing pointers takes an extra two keystrokes, and doesn't look as neat. Sometimes I like pointers though, like when (as above) I want to make a parameter optional. That can also be a big pain though, because it means you can't just pass a straight value then, you'd need to create a variable.
i.e.
int someParameter = 5;
myFunction(NULL, NULL, parameter, NULL);
as opposed to
myFunction(something, something, 5, something);
Just Google It. √
(\ /)
( . .)
c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.
><snip> to indicate whether the return value is valid or not
Or you could define a variable that is only used as a sort of poor man's null:
Code:#include <iostream> #include <cstdlib> #include <string> using namespace std; namespace { string null; } string& foo ( string& s ) { if ( rand() % 2 != 0 ) { return null; } return s; } int main() { string s ( "A string!" ); for ( int i = 0; i < 10; i++ ) { if ( foo ( s ) == null ) { cout<<"No string here!"<<endl; } else { cout<< s <<endl; } } }
My best code is written with the delete key.
Does that work? What if foo() returns an empty string anyways?
Just Google It. √
(\ /)
( . .)
c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.
>Does that work?
Yes.
>What if foo() returns an empty string anyways?
Then null should be initialized with a string that couldn't possibly be a valid return of foo. If any string is possible, then you could test the addresses.
My best code is written with the delete key.
Ah, and here we are back to pointers How DO they get by in pointerless languages? heh...
Just Google It. √
(\ /)
( . .)
c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.