user2687305
user2687305

Reputation: 89

Can a C++ reference parameter have the same name as the argument?

I'm rusty on references, but I know they are just another name for a variable. Going off that, what if you have a reference that's the same name? Why would it work/not work?

For example:

foo(int &a) {
   printf(a);
}
main() {
   int a;
   foo(a);
}

Thanks

Upvotes: 0

Views: 454

Answers (2)

Ali Asad
Ali Asad

Reputation: 157

Yes it will work.. int &a is local variable of function which will recieve just reference passed to it and it's scope is limited to this function only whereas a in Main function has scope within main function.

Upvotes: 0

LihO
LihO

Reputation: 42083

"Why would it work/not work?"

In terms of name of your argument: Yes, it will work. The a in main is a local variable, the identifier a, which refers to this variable is valid only within the same scope. In foo, there's an argument a, but this a is different identifier than the first one.


PS: I assume that this:

printf(a);

was meant to be:

printf("%d", a);

Upvotes: 4

Related Questions