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!
"Isn't it" is the most common definition for INT on Snapchat, WhatsApp, Facebook, Twitter, Instagram, and TikTok. INT. Definition: Isn't it.
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.
The int keyword is used to indicate integers. Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With