Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does int & mean

A C++ question,

I know

int* foo(void) 

foo will return a pointer to int type

how about

int &foo(void) 

what does it return?

Thank a lot!

like image 456
Alfred Zhong Avatar asked Jan 07 '11 19:01

Alfred Zhong


People also ask

What it means to int?

"Isn't it" is the most common definition for INT on Snapchat, WhatsApp, Facebook, Twitter, Instagram, and TikTok. INT. Definition: Isn't it.

What does int [] mean in C#?

int is a keyword that is used to declare a variable which can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of System.

What does int () do in C++?

The int keyword is used to indicate integers. Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.

What is the use of int?

The int() function returns the numeric integer equivalent from a given expression. Expression whose numeric integer equivalent is returned. This example truncates the decimal and returns the integer portion of the number. This example illustrates using the int() function to keep one decimal place and truncate the rest.


1 Answers

It returns a reference to an int. References are similar to pointers but with some important distinctions. I'd recommend you read up on the differences between pointers, references, objects and primitive data types.

"Effective C++" and "More Effective C++" (both by Scott Meyers) have some good descriptions of the differences and when to use pointers vs references.

EDIT: There are a number of answers saying things along the lines of "references are just syntactic sugar for easier handling of pointers". They most certainly are not.

Consider the following code:

int a = 3; int b = 4; int* pointerToA = &a; int* pointerToB = &b; int* p = pointerToA; p = pointerToB; printf("%d %d %d\n", a, b, *p); // Prints 3 4 4 int& referenceToA = a; int& referenceToB = b; int& r = referenceToA; r = referenceToB; printf("%d %d %d\n", a, b, r); // Prints 4 4 4 

The line p = pointerToB changes the value of p, i.e. it now points to a different piece of memory.

r = referenceToB does something completely different: it assigns the value of b to where the value of a used to be. It does not change r at all. r is still a reference to the same piece of memory.

The difference is subtle but very important.

If you still think that references are just syntactic sugar for pointer handling then please read Scott Meyers' books. He can explain the difference much better than I can.

like image 91
Cameron Skinner Avatar answered Sep 23 '22 09:09

Cameron Skinner