Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about pointers and references in C++

Tags:

I have a bunch of code like this:

#include <iostream> using namespace std;  void swap(int *a, int *b) {     int temp = *a;     *a = *b;     *b = temp; }  int main() {     int a;     int b;     a = 7;     b = 5;     swap(a, b);     cout << a << b;      return 0; } 

This code does the swapping process as what I exactly wanted to swap 2 numbers, but when I want two numbers from the user as follows;

int a; int b; cin >> a; cin >> b; swap(a, b); cout << a << b; 

the compiler gives me an error about int to int* error which is as expected. Why does the first code do the right swapping although I didn't use the method with & operator?

like image 333
w1LL1ng Avatar asked Nov 15 '12 17:11

w1LL1ng


People also ask

What is difference between reference and pointer in C?

References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.

Is it better to use pointer or reference?

References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

What are the problems associated with pointers in C?

2.2 Pointers Can Be Dangerous Because pointers provide access a memory location and because data and executable code exist in memory together, misuses of pointers can lead to both bizarre effects and very subtle errors. dangling pointers.


1 Answers

In the first example, std::swap is called, because of your using namespace std. The second example is exactly the same as the first one, so you might have no using.

Anyway, if you rename your function to my_swap or something like that (and change every occurence), then the first code shouldn't work, as expected. Or, remove the using namespace std and call std::cin and std::cout explicitly. I would recommend the second option.

like image 79
ipc Avatar answered Sep 23 '22 18:09

ipc