Lewis921
Lewis921

Reputation: 37

Suppose we have a C++ string called success. What is the difference between &success and success&?

Question: Suppose we have a C++ string called success. What is the difference between &success and success&?

This question is from my midterm review, I understand that &success is getting the address of the object. But I am not sure what success& is?

Upvotes: 0

Views: 201

Answers (4)

Amal K
Amal K

Reputation: 4919

The & has two meanings. I'm assuming that success is a variable and not a struct or class name as so: std::string success = "myString"

1. To refer to the address of the variable

If you refer to success as &success anywhere except in declaration or function parameter(formal argument) list, it is a reference to the address of that variable. In your case, it &success would return the actual raw memory address where "myString" is stored in.

2. Reference Variable

If you see the & where the variable is declared or in a function's parameter (formal argument) list as

std::string& success;

Or

void swap(std::string& success, std::string& failure);

it is the syntax for a reference variable which are basically syntax sugar for pointers. Such variables refer to the same values as other variables do and can be assigned only once through the assignment operator or member initializer lists.

Upvotes: 0

Saurav Rai
Saurav Rai

Reputation: 2367

I think you are mistaken with the following expression. The data type below means a reference to a string object whose contents will not be changed.

const string& 

Hope this will help you.

Upvotes: 2

rogme
rogme

Reputation: 84

If success is a variable then the expression success& is invalid and the compiler would complain, on the other hand if it is type success& would mean a reference to the type.

Upvotes: 2

eesiraed
eesiraed

Reputation: 4654

If success is a variable and not the name of a type then it's invalid syntax by itself.

Upvotes: 3

Related Questions