What does int & mean

73,554

Solution 1

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.

Solution 2

It returns a reference to an int variable.

Solution 3

This question isn't C/C++ at all, as C does not have references, only pointers. An int& is a reference to an int. Also, you don't need void, it can just be int& foo();

Solution 4

From Alfred's comments

This is what the document says, Texas instrument's TMS320C28x C/C++ compiler intrinsics, page 122, int&__byte(int, unsigned int), I guess it is different from PC – Alfred Zhong

From the manual:

int &__byte(int *array, unsigned int byte_index);

MOVB array[byte_index].LSB, src

The lowest adressable unit in C28x is 16 bits. Therefore, normally you cannot access 8-bit MOVB dst, array[byte_index]. LSB entities off a memory location. This intrinsic helps access an 8-bit quantity off a memory location, and can be invoked as follows:

__byte(array,5) = 10;
b = __byte(array,20);

This just means that the function returns a reference to an integer that acts like an 8 bit quantity. Because the value is a reference modifying will modify the object at the destination (just like the MOVB) instruction, while assigning to b will copy (just like MOVB) to the destination.

Share:
73,554
Alfred Zhong
Author by

Alfred Zhong

Updated on May 05, 2021

Comments

  • Alfred Zhong
    Alfred Zhong about 3 years

    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!