This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 7 years ago.
Can you tell me the difference between the source 1 and 2?
The book says the first one is call by address(pointer) and the second one is call by reference, but i don't exactly get those two sources.
Please explain those sources to me please, thank you in advance.
1.
#include <iostream>
using namespace std;
void absolute(int *a);
void main()
{
int a = -10;
cout << "Value a before calling the main function = " << a << endl;
absolute(&a);
cout << "Value a after calling the main function = " << a << endl;
}
void absolute(int *a)
{
if (*a < 0)
*a = -*a;
}
2.
#include <iostream>
using namespace std;
void absolute(int &a);
void main()
{
int a = -10;
cout << "Value a before calling the main function" << a << endl;
absolute(a);
cout << "Value a after calling the main function" << a << endl;
}
void absolute(int &a)
{
if (a < 0)
a = -a;
}
In terms of what happens at the CPU level, pointers and references are exactly the same. The difference lies in the compiler, it won't let you do a delete on a reference (and there's less typing)
So in your code both functions do the same thing.
Related
This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 1 year ago.
I have the following code
# include <iostream>
using namespace std;
void show (int list[], int len) {
for (int i = 0; i < len; i++) {
cout << list[i] << " ";
}
cout << endl;
}
void swap (int* a, int* b) {
cout << *a << ' ' << *b << endl;
int c = *a;
*a = *b;
*b = c;
cout << *a << ' ' << *b << endl;
}
void aFunction (int list[], int len) {
cout << "From aFunction ";
show(list, len);
swap(list[0], list[1]);
cout << "From aFunction ";
show(list, len);
}
int main() {
int list[] = {6, 4};
int len = sizeof(list)/sizeof(int);
aFunction(list, len);
return 0;
}
When I compile and run this I do not get any errors and I receive the output as
From aFunction 6 4
From aFunction 4 6
But when I change the following line in aFunction
swap(list[0], list[1]);
to
swap(&list[0], &list[1]);
it still compiles and give me the following output
From aFunction 6 4
6 4
4 6
From aFunction 4 6
What is going on? My initial thought was swap(list[0], list[1]) is right since arrays decay to pointers when passed to a function so we are essentially passing pointers to swap but then the cout in swap is not printed, which leads me to believe swap(&list[0], &list[1]) is right. If the latter is right, why the compiler does not raise any error for the first and why the cout in swap does not execute? Which one is right? What's going on????? I am compiling this program using g++ weird.cpp on a MacBook Pro. I would be really grateful for an explanation.
You're calling std::swap, not your own swap function.
std::swap takes two reference arguments of any matching type.
(This is why, IMHO, using namespace std; can be a bad idea. I prefer to qualify names with std:: explicitly.)
This question already has answers here:
Is there a way to access the value of a local variable that has become hidden inside another scope?
(4 answers)
Closed 4 years ago.
#include <iostream>
using std::cout;
using std::endl;
int a {1};
int main()
{
int a {2};
{
int a {3};
cout << ::a << endl;
cout << a << endl;
}
return 0;
}
the first output is 1, it's the value of a that defined before function main()
so is there any way to output the second a that defined in function main() in the inner block ?
thanks!
so is there any way to output the second a that defined in function
main() in the inner block ?
a{2} and a{3} are both in block-scope.
Thus, a{3} shadows a{2} in the inner-block.
To output the a{2} you just need to move the point-of-declaration of a{3}.
int a {2};
{
cout << ::a << endl;
cout << a << endl; // a{2} will be used here
// since a{3} is not defined here yet.
int a {3};
cout << a << endl; // a{3} will be used here
// since it's already defined at this point
}
This question already has answers here:
Arrays passed to function in C++ giving different lengths
(5 answers)
Closed 5 years ago.
Consider the code below. This generates the following output:
Length: 64
Testfn: 8
Length again: 64
I am having trouble understanding why the output at the test-function is not equal to the output at the main function. Taking into account that the output at the test-function is equal to 8, I assume that this is because sizeof(arg) gets the size of the pointer instead of the array itself.
This would all seem very logical to me, but why doesn't sizeof give that same value in the main function? And how would I fix it? I have tried several things with dereferencing, but this does not seem to give any difference whatsoever.
#include <iostream>
void test(int arg[]) {
std::cout << "Testfn: " << sizeof(arg) << std::endl;
}
int main() {
int int_arr[16];
std::cout << "Length: " << sizeof int_arr << std::endl;
test(int_arr);
std::cout << "Length again: " << sizeof int_arr << std::endl;
}
The function parameter
void test(int arg[]) {
is adjusted to pointer to type int. That is the following function declarations
void test(int arg[16]);
void test(int arg[]);
void test(int *arg);
are equivalent.
So inside the function there is used sizeof( int * ) that depending on the using platform usually equal to either 4 or 8.
You could declare the function in C++ like
void test(int ( &arg )[16]) {
std::cout << "Testfn: " << sizeof(arg) << std::endl;
}
that is to declare the parameter as reference to the array and in this case you will get the expected result.
If you use C++11 or higher, the std::array is what you need:
#include <iostream>
#include <array>
template<size_t N>
void test(const std::array<int, N>& arg) {
std::cout << "Testfn: " << arg.size() << std::endl;
}
int main() {
std::array<int, 16> int_arr;
std::cout << "Length: " << int_arr.size() << std::endl;
test(int_arr);
std::cout << "Length again: " << int_arr.size() << std::endl;
}
This question already has answers here:
Uninitialized values being initialized?
(7 answers)
Closed 8 years ago.
I'm doing some testing...
Firstly I post my source code
the .h file
class Complex{
private:
int r = 0;//initializer
int i ;
public:
Complex(int , int I = 0);
Complex();
void print();
void set(int, int I = 1);
static void print_count();
static int count;
};
the .cpp file
#include <iostream>
#include "complex.h"
int Complex::count = 1;
Complex::Complex(int R , int I){
r = R;
i = I;
count++;
std::cout << "constructing Complex object...count is " << Complex::count << std::endl;
}
Complex::Complex(){//default constructor
std::cout << "default constructor is called..." << std::endl;
}
void Complex::print(){
std::cout << "r = " << r << ';' << "i = " << i << std::endl;
return;
}
void Complex::set(int R, int I /*= 2*/){//will be "redefaulting", an error
r = R;
i = I;
return;
}
void Complex::print_count(){//static
Complex::count = -1;//jsut for signaling...
std::cout << "count is " << count << std::endl;
return;
}
the main function
#include <iostream>
#include "complex.h"
int main(){
Complex d;//using default constructor
d.print();
/*Complex c(4, 5);*/
Complex c(4);
//c.print();
/*c.set(2, 3)*/
c.print();
c.set(2 );
c.print();
std::cout << "count is " << c.count << std::endl;//c can access member data
c.print_count();
c.count++;//
return 0;
}
consider the Complex object d constructed with default ctor
because the data member r is initialized using with 0, when executing d.print(),
r is expected to be 0
and i isn't, so I expected it to be garbage value
but when I'm testing, one strange thing happens.
if I eliminate this and the following lines of code in the main file:
std::cout << "count is " << c.count << std::endl;//c can access member data
then d.print() will give the value of i as 32767 on my system, which I guess it's a garbage value;
but once that line is added, d.print() just give i's value to 0 on my system.
I don't get it. I hasn't set, modiify or initialize i's value, why should it be 0?
or, it is also a garbage value?
or, calling one of those function corrupts the value of i?
how is the thing run behind the scene here?
thx for helping.
0 is just as garbage value as any other. Don't make the mistake of thinking otherwise.
Formally, reading an uninitialized variable is undefined behavior, so there's no point in wondering about it: just fix it by initializing the variable properly.
This question already has answers here:
Function argument type followed by *&
(3 answers)
Closed 9 years ago.
I was looking at manual of ACE framework and came across this declaration
int ACE_Stream<>::get (ACE_Message_Block *& mb, ACE_Time_Value * timeout = 0)
I'm not able to understand what *& stands for. I know * is for pointer and & is reference. Can any one explain what is the meaning of this declaration.
Thanks in advance
So as #NPE said *& makes changes to pointer propagate back. But to understand I just wrote down some code sharing it so that it can help others understand this correctly
#include <iostream>
using namespace std;
class DoSomething
{
public:
int n;
DoSomething(int i){
n = i;
}
virtual ~DoSomething();
};
DoSomething::~DoSomething()
{
}
int dosomething(DoSomething * a)
{
cout << "Got value from caller: (in dosomething) = " << a << endl;
a = new DoSomething(25);
return 0;
}
int dosomethingElse(DoSomething *& a)
{
cout << "Got value from caller: (in dosomethingElse) = " << a << endl;
a = new DoSomething(15);
return 0;
}
int main(int argc, char *argv[])
{
DoSomething *d = new DoSomething(10);
cout << "Pointer to DoSomething: " << d << endl;
dosomething(d);
cout << "After dosomething value of d: " << d << endl << endl;
dosomethingElse(d);
cout << "After dosomethingElse value of d: " << d << endl << endl;
delete d;
return 0;
}
So as #NPE said here is out put of this
Pointer to DoSomething: 0x955f008
Got value from caller: (in dosomething) = 0x955f008
After dosomething value of d: 0x955f008
Got value from caller: (in dosomethingElse) = 0x955f008
After dosomethingElse value of d: 0x955f028
So indeed if I create a new instance inside function it will propagate only if I use *& and not just *
Thank you to every one for the answers.
I know * is for pointer and & is reference.
Correct. So what you have here is a pointer, passed by reference.
mb is a pointer that's being passed by reference. This means that if get() were to change the value of the pointer, the change would propagate back to the caller.