Parameters by reference to a C function - c++

I want to pass a value by reference in C. Are this two functions the same? Which is the difference? Is the same in C++?
void foo1(int * val1, int * val2)
void foo2(int &val1, int &val2)
Thanks,

References are C++ only (not C).
The implementations of the methods will be different, since dereferencing a reference is different from dereferencing a pointer in C++.
e.g.
ref.method();
vs.
ptr->method();
In both cases you're calling on the original object passed to the method, not a copy.

The second is not C, only C++. Passing by reference is in C emulated by passing the addresses of the values.

In C you can not do foo2, because there is no reference operator like in C++.
In C++ they are not the same either. References can not be NULL and they are constant. They can not point to another location after initialisation.

void foo1(int * val1, int * val2) is equivalent of
void foo2(int &val1, int &val2) in C. In both the case functions need addresses.
The 2nd one is used in C++. This can be used to pass the reference of any variable.
For example if you have a variable like int num1 = 10, num2 = 20; .
Then foo2(&num1 , &num2 ) needs foo2 in C++ but this will not work in C.

In C, there is no pass by reference. Instead you can pass the addresses to pointers, which essentially allows one to change the value of the variable passed.
The second function is in C++.
The two functions have a different signature, although they allow one to perform the same task.

Related

Why do functions in c++ need pointers to work (pass by value,pass by reference)

I have a question in c++.I 'am a newbie and was coding the other day in c++, more specifically i was trying to implement some functions (1 that adds 2 numbers and 1 that swaps 2 numbers).
I realized that the code implementing the addition function didn't need no pointers (void func), while the swap function only worked after i used pointers both in parameters of the function and variables used to implement it(int type func).
Any suggestions as to why is this happening?
Does it have to do with passing by value or by reference and if yes when do we really need to use pointers in these functions?
Per your title, functions don't need pointers to work:
int add(int a, int b)
{
return a + b;
}
In C++ the rule for passing parameters is to pass a copy of the variables, unless told otherwise. When passing by copy (a.k.a. pass by value), the parameters cannot be modified.
Rather than passing copies of large data structures (anything that doesn't fit into the processor's register), C++ allows you to pass a reference to the object. The reference is usually a lot smaller in size than the object it refers to. Also, passing by reference allows you to modify the original object:
bool divide(int a, int b, float& result)
{
if (b == 0) return false;
result = static_cast<double>(a) / static_cast<double>(b);
return true;
}
Passing by pointers is similar to passing by reference. However, a pointer can point to anywhere.
Functions take arguments because they do not have direct access to your variables. When you pass only the values to a function (i.e. void func(int a, int b){ ... }), the function still does not have access to your variables. What you are doing is basically creating new variables within the function that have the same values as the ones you passed in.
When you pass a pointer, though, you are telling the function where the actual variable is in memory, so it can tinker with the variable even though it is not in its scope (this can be easy to mess up and is the reason higher level languages don't have user-level pointers).

Why does passing arguments by reference work in C++ the way it does?

Let's say I have a function:
void function(int& i){};
and a variable:
int j = 2;
I know that I can use my function:
function(j);
But it is inconsistent: the compiler should notice that the function expects a reference, not a normal variable and that I tried to use a normal variable instead (int& != int) and abort the compilation. However, people who invented C++ implemented this behaviour. It seems illogical to me.
Why is it possible? Is there something I don't understand or is the sytax of C++ really inconsistent?
Note: I'm not asking when I should pass arguments by value ad when by reference or what's the difference between these methods (there are pleny materials covering this topic). I just want to know why it works the way it does - the syntax seems contradictory to me.
Why don't I need a reference to pass an argument by reference?:
int& k = j;
function(k);
Edit: I don't have ny doubts about binding references to variables, I think the following piece of code is clear and logical:
int& k = j;
The only doubts I have refer to passing arguments by references:
void function(int& i){};
int j = 2;
function(j);
Why don't I need a reference to pass an argument by reference?
The short version is that all the ways that matter here, i effectively already is a reference.
The long version is that when you declare an argument of type int&, this does not mean "an integer reference". It means "an integer lvalue", which is a different thing. An integer reference is only one way to produce an integer lvalue- there are others, as you've noticed. C++ expression value categories and types interact but are not the same system. i is an integer lvalue; therefore it will accept that as the argument.
A reference isn't an object by itself, it just creates another name for an object. An alias.
With int& k = j; you say that k and j are different names for the same object. This is similar to person& Bob = Robert;, when using a nickname for a person.
So, why would it then make a difference if you pass k or j as a parameter to the function? They are the same thing. Just like Bob and Robert.
The answer is so clear. The c++ compiler doesn't take '&' like a reference. They are both the same func(int &a) or func(int a). The compiler takes it like a variable in the two situations. But if you define the func like func(int *a) that means I want the address of the 'a' argument. Did you see the diffirence. The compiler hierarchy of c++ is a little bit diffirent from the c compiler.

Pass by pointer & Pass by reference [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
Are there benefits of passing by pointer over passing by reference in C++?
In both cases, I achieved the result.
So when is one preferred over the other? What are the reasons we use one over the other?
#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x=*y;
*y=z;
}
void swap(int& x, int& y)
{
int z = x;
x=y;
y=z;
}
int main()
{
int a = 45;
int b = 35;
cout<<"Before Swap\n";
cout<<"a="<<a<<" b="<<b<<"\n";
swap(&a,&b);
cout<<"After Swap with pass by pointer\n";
cout<<"a="<<a<<" b="<<b<<"\n";
swap(a,b);
cout<<"After Swap with pass by reference\n";
cout<<"a="<<a<<" b="<<b<<"\n";
}
Output
Before Swap
a=45 b=35
After Swap with pass by pointer
a=35 b=45
After Swap with pass by reference
a=45 b=35
A reference is semantically the following:
T& <=> *(T * const)
const T& <=> *(T const * const)
T&& <=> [no C equivalent] (C++11)
As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.
An advantage over pointers is that you need explicit casting in order to pass NULL.
It's still possible, though.
Of the compilers I've tested, none emit a warning for the following:
int* p() {
return 0;
}
void x(int& y) {
y = 1;
}
int main() {
x(*p());
}
In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.
Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.
Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.
References have a couple more advantages compared to pointers (e. g. they can't be NULL, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.
Pass by pointer is the only way you could pass "by reference" in C, so you still see it used quite a bit.
The NULL pointer is a handy convention for saying a parameter is unused or not valid, so use a pointer in that case.
References can't be updated once they're set, so use a pointer if you ever need to reassign it.
Prefer a reference in every case where there isn't a good reason not to. Make it const if you can.
Here is a good article on the matter - "Use references when you can, and pointers when you have to."
Use references all the time and pointers only when you have to refer to NULL which reference cannot refer.
See this FAQ :
http://www.parashift.com/c++-faq-lite/references.html#faq-8.6

Why do certain C/C++ functions use pointers as parameters?

I'm coming from C# and I'm learning C++ (with this tutorial) so I have a relatively insubstantial amount of knowledge on memory, but the only use I see in pointers is "saving space" and iterating through arrays. So why do functions like the scanf function take pointers as parameters? For instance:
printf("What's your name?: ");
and then:
scanf("%s",&userName). Wouldn't it make more sense to just pass the variable itself as an argument? The C book I was looking at said that using the variable itself would produce unexpected results, but I don't see why. Could anyone please enlighten me in a C++ fashion? I switched from learning C because I realized how much I love OOP.
There are 3 different ways of passing a variable to a function in C++, pass by copy, pass by reference and pass by pointer.
#include <iostream>
void passByCopy(int a)
{
a += 1;
}
void passByReference(int &a)
{
a += 1;
}
void passByPointer(int *a)
{
(*a) += 1; // De-reference then increment.
}
int main()
{
int a = 0;
// Passing by copy, creates a copy of the 'a' object, then sends it to the function.
passByCopy(a);
std::cout << a << std::endl; // Outputs 0
// Passing by reference, causes the 'a' object in the function to reference the 'a'
// object at this scope. The value of 'a' will change.
passByReference(a);
std::cout << a << std::endl; // Outputs 1
// Passing by pointer, does almost the same thing as a pass by reference, except a
// pointer value can by NULL, while a reference can't.
passByPointer(&a);
std::cout << a << std::endl; // Outputs 2
}
With scanf, the purpose of the function is to pass values to variables in the current scope, so it can't use pass by copy. It doesn't use pass by reference for two reasons, one is that it is an old C function, so pass by reference didn't exist when it was written. The second is that it is a variadic function, which means that internally the function receives a list of pointers rather than a series of arguments.
C and C++ pass variables by value; the formal parameter is a different object in memory from the actual parameter. Thus, if the formal parameter is modified in the function, the value of the actual parameter isn't changed.
By passing a pointer, the function can modify the contents of the actual parameter:
void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
...
swap(&x, &y);
Thus, writing to *a in swap is equivalent to writing to x in the caller.
Pointers in C serve three main purposes:
Faking pass-by-reference semantics, as above (as Karl notes in the comments, C++ has a mechanism that supports true pass-by-reference);
Tracking dynamically-allocated memory (the memory allocation functions malloc, calloc, and realloc and the C++ new operator return pointer values);
Building dynamic data structures (trees, lists, queues, stacks, etc.).
All parameters are passed by value in C. If you want to pass by reference, you need to explicitly pass the address of the variable in question. Passing by reference is important when you want the function to modify the variable passed in.
C++ has references, but since C++ code often calls C library functions, you still see the same syntax used in C++ sometimes.
In your specific example, scanf is part of the C standard library. C does not have a string class, so strings are represented as arrays of characters.
In C, the address of the first character is usually passed when strings are required. This can either be &str[0] or str. I'm not sure it's correct to have &username if it's expecting a char *, I guess it depends on username.
C has no concept of passing by reference and can return only a single value. The traditional purpose of passing by pointer is therefore to allow the called function to write to a variable so that the caller can read what has been written.
C++ has the ability to pass by reference, but scanf and printf are C functions that are also available when building as C++ so that isn't available to them.
EDIT: to explain further, even putting beside the variable arguments issue, in the following code:
void calledFunction(int var1, int var2)
{
var1 = 23;
var2 = 19;
}
void callingFunction(void)
{
int v1 = 9, v2 = 18;
calledFunction(v1, v2);
printf("%d %d", v1, v2);
}
The output is "9 18". calledFunction gets local copies of v1 and v2 because C passes by value, meaning that the values of v1 and v2 were passed in, but no other link was kept to the originals. So the fact that it modifies its copies has no effect on the originals.
In C there are no references, all the arguments are passed by value.
If scanf would be in C# then its parameters would be preceded by out or ref keyword and no pointers would be needed. Passing pointers allow the scanf function to write some values to whatever place the pointers point to.
In C++ however there are references, though different from what you know from C#. Nonetheless if you'd use iostream library and not stdio which was inherited to C++ from C, then you wouldn't have to use pointers in this way. You'd just write:
String username;
cin >> username;
One other use of pointers that I don't see mentioned in the other anwers here is that it's one of only two ways that a C function can return multiple values. A C function is defined to return a single object, but it can receive many arguments. If your multi-valued function always returns the same set of values, it's a question of convenience whether to wrap the values in a struct and have the function return the struct or have the function receive pointers through which it can write the values.
The pointer-parameter option becomes much more attractive if the function also needs to return a status or error code (because it's silly to write that through a pointer, forcing the caller to allocate another variable and obstructing standard idioms like if(f()==ERROR)...). And if the set of values is not predictable at compile time (like scanf, which must interpret the format string at runtime), then pointer-parameters become the only (sensible) option.
Edit: In your example, scanf("%s",&username); assuming username is an array type or a pointer to storage suitable for holding a character string, you don't need to pass the address. If it's an array, it will be passed as a pointer implicitly. And if it already is a pointer, taking the address yields a pointer-to-pointer, which is not suitable to hold a string. So drop the & here.
scanf is a C function. C doesn't have references, so it has to use pointers in order to write to arguments. Also, scanf is a varargs function, so it takes variable numbers of arguments. And varargs functions can only take built-in types: pointers (to anything), integers, doubles.

Prefered way to declare pointer/reference variables?

Note: I am using the g++ compiler (which is I hear is pretty good and supposed to be pretty close to the standard).
Not trying to start a grammar war, but just a random question... What is the ideal way to declare a pointer?
int* pI = 4;
int *pI = 4;
(or my favorite, I know it's non-pretty, but I like it):
int*pI = 4;
Same question stands for references:
int& rI = 4;
int &rI = 4;
or
int&rI = 4;
Maybe there is no right answer. Similarly, should I care whether a constant integer is declared as:
const int I = 4;
or
int const I = 4;
I'm fine with not caring...
I do like the way a const function is declared by having a const after the last parenthesis.
And I believe a constant function has a distinct function signature than the similar non-const function (i.e. the const-nesss is part of the function signature, unlike most sources that say it just depends on the arguments type and the return type).
Is this right? Should I care?
I prefer
int* a;
int& b;
for the following reason: the type is int* and not int. For me - the type belongs together and needs to stand separate from the name. I know this introduces some problems with
int* a, b;
but that's why I don't declare to variables in one line.
Other than that - like VJo said: stick to the coding standard. If everyone around you does it one way, don't do it the other.
Coding standards might tell you how to declare or define your variables.
Other then that, use whatever suits you better.
And I believe a constant function has a distinct function signature than the similar non-const function (i.e. the const-nesss is part of the function signature, unlike most sources that say it just depends on the arguments type and the return type).
A constant function has a keyword const which is appended at the end of it.
int doSomething() const;
It means that the function will not alter the state(members) of the class.
Mentioning const on an argument implies that the function will not alter the state of that variable(param in below example) being passed to the function.
int doSomething(const int param);
Mentioning const before the return type applies to the type being returned by the function.
const int doSomething();
Implies the function returns a const integer value.
So yes your understanding is correct. And there is no other way to declare a function const except putting a const after the last paranthesis.
Also, note that const member function can be only called on a const object, while a non const member function can be called by const as well as non const objects of that class.
As far as the way of declaring, Each organization have their own coding guidelines and you should stick to that, Yes there is no distinct advantage of using those contructs you mentioned in either way with respect to compiler optimization or treatment. Just follow what you like or what your organzation wants you to follow.
Bjarne Stroustrup uses:
int* a;
so, that's good enough for me.