Go Down

Topic: Problem passing function argument as reference (Read 1 time) previous topic - next topic

WizenedEE


Can someone tell me why the sscanf function (for example) require that we pass referenced parameters with a '&' in front of them, like:
Code: [Select]

sscanf( str, "%d", val); // doesn't work

sscanf( str, "%d", &val); // work



References didn't exist in C so they had to use pointers.

I think it'd bad form to have your function accept a non-const reference because most things are passed by value so the caller doesn't have to worry about it getting modified and then can't tell when it might be. Adding the & character makes it much clearer that it will be modified.

Passing by const reference is fine so that huge objects don't need to be copied if they won't be changed anyway.

PeterH

References are just a bit of syntactic sugar round pointers, aren't they? I mean, the semantics of passing a value by a reference type are identical to passing it via a pointer, it just avoids the pointer syntax.
I only provide help via the forum - please do not contact me for private consultancy.

Nick Gammon


I know but other functions using referenced parameters doesn't need the '&' in front of parameters..like this:


sscanf is a C function. References were introduced in C++.

Quote
References are just a bit of syntactic sugar round pointers, aren't they?


To a certain extent, although since you can't change the "underlying" pointer the compiler lets you use references where it wouldn't let you use pointers (eg. for things that are const).

guix


Go Up