Reference parameter

I know the pass by reference i c++ like

1
2
3
int func(int& x){
return x;
}


But on the book i am currently reading. There are somethings that the author doesnt explain like this

1
2
3
int func2(int&){

}


If i am going to use that func2() how am i going to have a return value on it?
returing & is invalid.

Sample on the book
 
bool lengthCompare(const string &, const string &)

Is the
bool lengthCompare(const string &, const string &)
written as
bool lengthCompare(const string &, const string &);
or as
1
2
3
4
bool lengthCompare(const string &, const string &)
{
  // code
}


The example you gave is a way of declaring a parameter that isn't actually used in the function, I know that sounds wrong, but it happens. If you don't put the parameter variable name in, the compiler wont complain when you don't reference it.

@keskiverto

It is writen as

bool lengthCompare(const string &, const string &);
@Jaybob66

If it isnt used. Is there a reason someone would use it? I mean as a beginner its on c++ i obviously think its has something to do with the function.
That is a declaration. The caller of a function uses the declaration to ensure that types match. The caller does not need to know the names of the parameters. Default values for parameters, if any, have to be in the declaration.

The implementation needs the names. How does it look in your example?


Older MSVC had trouble deducing types for template functions and occasinally resorted to dummy parameter just to specify a type. Templates are not yet on your plate.
like keskiverto says, parameter names aren't necessary for declarations. personally i think its lazy to omit them, but each to their own.

The coding standards where I work says that I have to put the names in, but my previous employer didn't care either way. I guess its personal taste.

If you do put the names in, then you are giving more meaning to your declaration.

eg;
float TimeToTarget(double&);
vs
float TimeToTarget(double& distInMetres);
@jaybob66 and keskiveto

I cant see any example on the book. Could you give me a simple example?
The only thing that comes to my mind when i see this code

float TimeToTarget(double&);

base on your explanation is that if for example i declared a function at the bottom of the main function then declare the name of the function in top of main

like this

1
2
3
4
5
6

TimetoTarget(double&); // this is the one that comes to my mind

int main(){
......
}


1
2
foat TimeToTarget(double &burger){
}
Yup i get it.. Basically what I had in my mind is correct. So it is only a declaration..

Thanks guys for helping
Topic archived. No new replies allowed.