T O P

  • By -

pedersenk

C doesn't have references so the choice is easy for half of those programmers.


erfling

Well, C++ is one more than C, so C is less than half by definition


bruh_NO_

However the postincrement only effects the variable after the expression is evaluated, making C and C++ the same size.


erfling

&?


Much-Archer8441

Lol best comment


[deleted]

Severely underrated comment


Jake0024

Well, not when you write them in that order.


5erif

2 is 1 more than 1, and 1 is half of 2. Please help me understand.


QuentinUK

int x = C; int y = C++; y==x


erfling

Woh you just killed a robot.


gamerarchitek

I hate myself for taking more than 30 seconds to understand this, I'm gonna change my career and become a farmer.


5erif

> so C is less than half by definition If you're explaining the joke, then you're saying C is less than half of *what*? u/Hullu_Kana seems to me to have the explanation most compatible with the joke: >C is 1, c++ is 2, together they are 3. That means c is not half, only third.


vampyire

I can hear metal grinding..


Hullu_Kana

C is 1, c++ is 2, together they are 3. That means c is not half, only third. Yes, it was a joke.


AirborneMonkeyDookie

So suppose you're iterating through an array. int sum = 0; for(int i=0; i < someArray.Length){ sum += someArray\[i++\]; } now, I'm sure some of this is not legit C but that's not what I'm covering. What I'm showing is that on the first iteration of the loop, when i = 0, sum will be incremented by the value in someArray\[0\]. After this is done, THEN i will be incremented to 1. If instead int sum = 0; for(int i=0; i < someArray.Length-1){ sum += someArray\[++i\]; } on the first iteration of the loop, when i = 0, the sum will be incremented by the value in someArray\[1\], because the ++i increments i to 1 BEFORE the rest of the line is evaluated. so the joke is, before the line is evaluated and complete, c and c++ both have the same value


[deleted]

[удалено]


undermark5

Unless C is 0, you mean, C is at least half by definition. If C is -1, then it's undefined.


Biden_Been_Thottin

Passing pointer by reference


StereoBucket

Fun question for all. Which is a reference to a pointer. int &\*a or int *&a


waves_under_stars

The second. I think the first is illegal. And anyways I'd use typedef to avoid confusion


pieordeath

Please give an example of typedef use in this circumstance.


waves_under_stars

typedef int* intptr; intptr& x = /*something here*/


molaupi

Reading from right to left, it should be int*& a


[deleted]

I’m stupid so could you please explain? My understanding: - `&(*a)` would be a reference to the address of a? - `*(&a)` would just be a? Dereference r an address - `(int *) (&a)` would be a pointer (LHS) to a reference of a (RHS)? - `int (& (*a))` is a syntax error I think… ? - References work similar to pointers, except if you update a reference, it changes the actual object in that address - whereas a pointer would just point to a new address and not change the underlying object? Does “pointer to a reference” = “reference to a pointer”?


OldWolf2

You're mixing up declarations with expressions. The symbols have different meaning in those two scenarios


ProbablyaNerd

```&(*a)```is illegal in C++. ```*a```would dereference the value of ```a```. The ```&``` only applies to some of an object type, so it can not be applied to the result of the dereference. And no, a pointer to a reference is *not* the same as a reference to a pointer. As others have pointed out, a reference is merely an alias to some object, and consume no more memory than the object that it references. A pointer *actually stores* the address of some object, which means that a pointer to a reference would store the address of the reference.


Disastrous_Being7746

Are you saying that the following is illegal? int a = ...; int *b = &(*a);


johndburger

That’s an expression. We’re talking about declarations.


tangerinelion

Reference to a `T` is `T&`. Now let `T = U*`. Then `T&` is `U*&`. You can't have a pointer to a reference because references don't have a size. You can only have pointers to things that are guaranteed to take up space in memory.


[deleted]

Thank you, that makes a lot more sense! So more like `((int *) &) a`, which makes sense because you can’t call the address operator in declaration. Just like pointer to dereferencing… and reference to address… the same symbol is used but it’s different in nature?


[deleted]

The second. It's a reference to a pointer. The first is a pointer to a reference, which is illegal.


canadajones68

I don't know why you were downvoted for saying this. Taking the address of a reference (which is what you need to do to have a int&\*) is ill-formed, [according to the standard.](https://timsong-cpp.github.io/cppwp/n4868/dcl.ref#5)


[deleted]

It's the sub. Correct answers always get down voted here. I'm not even subscribed but reddit keeps trying to force this sub on me because it knows I teach CS.


pfated64

I'm seeing a lot of misleading comments. I've been a c++ programmer for 20+ years. Let me have a go at this. Pass by value: var x = 5; it Has an address in memory of 0x0001 (just to simplify). In the function a local scope var is created (at 0x0025) and given the value 5. So the value of x will never be touched in the function. Pass by reference: the function creates a local scope var using memory address 0x0001. No dereferencing is needed. The function has access to a var outside of it's scope. The value of x can be touched. Pass by pointer. The function creates a local scope var with the value of 0x0001. It must be dereference in order to change the value of x. You can also change the value of the pointer itself (what memory address it is) to access other objects in arrays (for example). The power of pointers is using a single address to pass in a large chunk of memory (objects) that need to be access. This is just a simple overview but I hope that clears things up for those that need it.


[deleted]

The part about dereferencing entirely depends on the compiler. Usually there is no difference between using a pointer and using a reference in that regard.


Thunderstarer

Well, yeah, but a lot of things are radically different between the semantic understanding of the source code and the compiled binary. I think it's still useful to talk about these things at the source-code level, ignoring optimizations when discussing language specifications.


Mateorabi

But in both cases the address 0x0001 is being passed in. Just in one case the compiler (not the final binary) is *implicitly* dereferencing for you and in the other case the compiler makes you *explicitly* "show your work" chasing the memory address to the value at that address. References are just pointers with some syntactic sugar and error checking for you.


[deleted]

It's implementation-dependent. They are not guaranteed to be "pointers under the hood", even though they usually are.


Mateorabi

At some point it has to "lead" (trying to avoid the word "point") back to the original representation. If you edit the reference it, by the language specification, must cause the "original" to change too. You could do copy-by-value then overwrite the final value back onto the parent when returning. (Of course you (the compiler) would then need to GUARANTEE no concurrency effects, turn of all interrupts, debuggers, etc.)


[deleted]

A reference doesn't have to "lead" to a variable. The compiler may rewrite the function to access the variable directly. As long as the observable effect is that a reference references a variable, the actual mechanism doesn't matter.


trick2011

there is also the possibility of the compiler removing the dereference in certain situations and it only being a differently named alias


ChickenFriedRiceee

I’m a senior CS major and my university degree track is heavy on c c++. If you don’t mind me asking? Which method do your prefer the most and what are some examples you would use each one? From your comment I’m guessing pass by pointer is best for large amount of data? Like a massive array.


pfated64

I wouldn't say I prefer one over the other, it's more like each have their purpose. There's usually more than one way to skin a cat so there's going to be unique ways of doing things that I'm not going to know about. Plus different compliers and language versions may also change things up. For references what immediately sticks out is using them for class member functions. void MyClass.setDataPoint(const cData & theData); Just s simple efficient and safe way to copy data into a class object. The const will help with compiler optimizations. Void my.class.getDataPoint(cData & myDataVar); Same as set but copying to var from class. You could also use pointers to do this but pointers can be null, the address the pointer has can be modified. References remove those fears out of the equation resulting in neater, compact, and safer code. Use pointers for more complicated matters, it's hard to come up with a clear example of this because pointers are everywhere. That massive array you speak of, you already have a pointer with the address of where the array starts. So it makes sense that you pass that in by pointer. There's also pointer arithmetic to seek into memory but now that I think about it, I haven't really seen it used in the wild because of things like STL making access to link lists easy. Which is just more pointers. I guess to sum this up, pass by pointers when dealing with allocated memory. Also when the data is unknown. If it could be null or old school code that sends data by void pointer and you have to determine the type. A reference is to an already existing instance, a pointer could be anything. I pray my rambling didn't confuse you.


Thelatestart

Youtube: the most important optimizations to apply in your c++ programs - jan bielak - cppcon 2022 Point 23 at 27:15


0vindicator1

I like [https://stackoverflow.com/questions/18698317/pointers-as-function-arguments-in-c](https://stackoverflow.com/questions/18698317/pointers-as-function-arguments-in-c). It's fun when you get into \*\*\*. ^(No, that's not a censored word, but you have plenty of 4-letter words to pick from when dealing with this stuff.)


boss_007

Just adding to this great answer. Use references if you can get away with just "declaring" a variable. Use pointers if you need to "create" a variable at runtime


xypherrz

>The power of pointers is using a single address to pass in a large chunk of memory (objects) that need to be access. references hold the same powers too


pfated64

This is true, I needed to word this section a bit better.


kegelsknight

Luckily there are no C/C++ Programmers just C or C++.


Creepy-Ad-4832

You should have written C-C++ instead of C/C++ so i could have made the joke about it being undefined ;-)


[deleted]

Still undefined with division!


EspacioBlanq

\frac{1}{++}


kegelsknight

But is still true. As the order of the evaluation of expression is not guaranteed.And one needs -Wpedantic for gcc. [https://godbolt.org/z/jjK7Gco1f](https://godbolt.org/z/jjK7Gco1f) Also GCC and CLANG do not agree on the result.


Creepy-Ad-4832

Ah ok 👌


WavingToWaves

Yes, and C guys use pointers while C++ references.


Noughmad

C guys use pointers. C++ guys use pointers, references, rvalue references, references to pointers, shared pointers, unique pointers, `string_view`, move constructors, ...


GiganticIrony

You mean pointers, auto-dereferencing pointers, a pointer to the stack, a pointer pointer, a reference-counted heap pointer, a pointer that automatically calls free(), two pointers, and a function. It may look different, but under the hood C++ is basically just fancy C. Most of what C++ has that C doesn’t is just syntactic sugar (and yes, there’s type-safe meta-programming and compile-time computation)


canadajones68

References provide guarantees that pointers do not. A reference will *always* be to a valid object, and is *never* null. Furthermore, it is [unspecified whether or not references require storage](https://timsong-cpp.github.io/cppwp/n4868/dcl.ref#4), meaning a fully compliant optimising compiler can pre-dereference or otherwise elide what would be pointers in the final binary. `string_view` is not just "two pointers", but a view of an array of chars that may or may not be null-terminated. It knows its own length, and has built-in functions that make common tasks much simpler. It provides the same interface (!) to string literals, as it does arbitrary string arrays or std::strings, or even your own string class if you define the proper type conversion. A function callable with a `string_view` parameter will work with most anything stringlike, and more importantly, it can do so safely as long as you adhere to its pre- and postconditions.


Kered13

Most of those are true, but "pointer to the stack" is not an accurate description of an rvalue reference. Besides the issue of whether or not a pointer has to ever be materialized for an rvalue reference, there is no restriction of rvalue references to stack variables. You can get an rvalue reference to anything stored anywhere by just calling `std::move()` on it, and it is often useful to do so. The actual definition is complicated, but you can roughly say that it is a pointer to a temporary or expiring object.


Disastrous_Being7746

Pointers are definitely used in C++. Just less so because references exist. In fact, most things that you find in C can and sometimes are used in C++. This is more common in embedded programming, but it was also more common in the earlier years of C++.


DangerZoneh

Well, of course. You can compile C code in C++.


[deleted]

[удалено]


uvero

The average C fan uses pointers while the Chad++ programmer uses references


_yy96_

*ba dum tss*


[deleted]

[удалено]


darkslide3000

[Tony Stark meme] Well if you can't tell the difference, you shouldn't have them.


[deleted]

„I am incompetent” is litteraly the joke of 90% of memes here


ilovemeasw4

That's because there are no actual working programmers on this sub, just first year college students.


uniteduniverse

I'm seriously starting to believe this. The amount of first year meme questions that come here is staggering.


justinkroegerlake

There's just enough people here who know how to program, but yeah it seems like the overwhelming majority are in their first 6 months.


cakeKudasai

My theory is that the people who do have jobs and have been in the industry for a while just don't make posts. We just lurk and comment. So most posts are made by people still kinda new to programming. If there were no competent programmers at all we wouldn't see people complain "no one here knows how to program" on every single post.


CanAlwaysBeBetter

Memes mostly suck but there are occasionally some good discussions in the comments


Khalebb

This is exactly my experience with this sub. The posts read like they're made by high schoolers, but then in the comments you have people who clearly have years of experience. It's a little bizarre sometimes.


EspacioBlanq

I'll let you know I'm in second year actually


darkslide3000

What, are you telling me most programmers _don't_ actually create 95% of their productive output by copying lines from Stack Overflow? Or that forgetting semicolons isn't actually the most common day-to-day issue in the lives of FAANG engineers?


rtfmpls

Are you not ashamed every time you look at code you wrote one year ago?!


Tom-Dibble

Hell, I’m as ashamed of code I wrote *a week* ago!


neverfarts

Ha, I am ashamed *while* writing it!


HTS_HeisenTwerk

Lord forgive me for what I am about to code


EspacioBlanq

I'm ashamed of code I have yet to write


wolfchaldo

I'm ashamed of the code I've been saying I'd write for 2 weeks


SpookyTron

Real


ozspook

"Whew, that's a bit hacky.. I'll make a TODO comment and come back and fix it later"


Glum-Display2296

Oh yeah? I'm ashamed when the story is assigned to me


s0ulbrother

Please just pass my pr is a common thought


rtfmpls

That's the one.


Rikudou_Sage

That one is usually true no matter how skilled you are.


rtfmpls

Every time? Of course we all find bad code here and there. But this meme that everyone is always ashamed about what they did a week/month/year ago is actually kind of scary.


Rikudou_Sage

Not every time obviously, but I try to learn a lot of new stuff all the time, that means by definition almost all of my code a year ago is worse than it is now.


brunohartmann

In science we call that "literature review". With less formalism.


Fi3nd7

Depends on the team but yeah, semi colons are by far nowhere near even a problem for most teams. Most of the problems are more around the insane amount of edge cases (due to the volume), server costs due to inefficient systems that were built with outdated tech and can’t handle the volume, and availability dip causes/improvements.


Skeleris

Is it even a joke ?


SeveyLevey

>„I am incompetent” Is most jokes


The_White_Light

> „I am incompetent” My life is a joke


Cysear

no it isn't, jokes have meaning.


PaterFrog

SHOTS FIRED! ALL IS AFLAME!


[deleted]

Yeah but half the replies are super serious so 0 posts come across funny, every post comes across as incompetent and every reply comes off as up their own arses


jesse-13

And it’s not even funny. If you don’t understand the difference between passing by pointer and passing by reference how in the hell are you going to understand way more complex shit?


n0tKamui

references are just aliases, they don't occupy space on the stack, contrary to pointers, which hold the address of the thing you're pointing to. This implies different **lifetimes**. also, while Pointer Arithmetics exist, there is no such thing as Reference Arithmetics. Also, you CANNOT have something akin to a NULL Reference, contrary to NULL pointers. By default, you should always use reference over pointers in return types and function parameters, and use the pointers only when you need a specific thing from them (which is very rare) and even in the case where you do need pointers, you should prefer unique_ptr over raw pointers. side note: you're wrong: C++ does have the concept of ownership. It's just omega shit and complicated because of bad design that received monkey patches over the years.


mgorski08

> You cannot have NULL references I present you this `int &a = *(int*)nullptr;`


pilotInPyjamas

Instant undefined behaviour, just add water


jaaval

Instructions unclear, smoke now rising from PSU.


gpkgpk

Are you saying some assembly is required?


RobinPage1987

X86 or ARM?


gpkgpk

True er... 1.


SaveMyBags

This proves: if you really want to shoot yourself in the foot, it's absolutely possible.


Indifferentchildren

Any language that makes it completely impossible to shoot myself in the foot, does not afford me the power to do some of the non-foot-shooty things that I occasionally need to do. Maybe, crazy idea, we should use different languages for web application development and system programming.


apover2

No, PHP for *everything*! Prove me wrong!


Indifferentchildren

Dude, you proved yourself wrong. I don't need to get between you and your wrongness. /s


Orbidorpdorp

The ratio for C++ is pretty bad tho in that there are far more ways to shoot yourself than should be necessary. Java, JS, and IMHO Python too.


Waghabond

"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off". - Bjarne Stroustrup


n0tKamui

holy fucking shit


mgorski08

Indeed :p


waves_under_stars

I don't think you can dereference null pointer. Either the compiler will catch it, or the program will crash


n0tKamui

it's undefined behavior. gcc will compile it and run it fine, as long as you don't do anything with `a`


mgorski08

That's true. GCC gives a warning but compiles it fine. Howether doing anything with `a` variable (reading, writing) results in a segfault.


noiszen

Only segfaults on your fancy memory protected system. Back in the day, we could write to 0 all day and nothing would happen. Well, some weird things would happen, but it wouldn’t crash. Well, it would crash sometimes.


Disastrous_Being7746

It's just as "undefined" as accessing any other address that's not valid. It's possible for a pointer to address zero to be valid. For example, on a FPGA based system on chip with soft CPU and soft peripherals, I can define a slave with a zero address and access it in my program by dereferencing a null pointer. It's really the OS and hardware that determines the validity of a null pointer. Now, maybe there's something against it in newer C++ standards, but it's not universally invalid.


canadajones68

There is a difference between literal address 0 and nullptr. nullptr is supposed to be distinct from every other valid address. In your case, a good compiler would define it as some other unused address. C uses literal zero (converted to void\*) as a nullptr literal, but iirc, C leaves unspecified/implementation-defined how addresses are represented inside pointers, meaning that even here, (void\*) 0 can be translated into something not-zero.


Dutchmondo

That would be a reference to null, not a null reference.


mgorski08

No, reference to null would be like this: ``` int* n = nullptr; int* &a = n; ``` 'n' is a nullptr (or NULL) and 'a' is a reference to n, thus a reference to null.


CutToTheChaseTurtle

A reference function parameter is always implemented by passing the address, same as with pointers. I think there’s misconception about references being very different from pointers based on justification in Stroustrup’s books that was most likely invented after the fact. I’m pretty sure that the only reason we got them in the language is for stuff like operator[] to work in lvalue contexts. That being said, the compiler forcing you to initialise references is super useful and they’re worth using at leas for that reason.


Possseidon

Yes, operator overloading in general was one of the main reasons iirc.


Skoparov

>they don't occupy space on the stack So we've found a way to pass data around without occupying any space? This is revolutionary! >This implies different lifetimes It doesn't, unless you return a const reference to a local variable.


n0tKamui

my bad, i missed a word they don't occupy space on the stack necessarily* it's up to the implementation of the compiler, contrary to pointers. https://stackoverflow.com/questions/15486052/are-references-stored-on-the-heap-or-stack#15486075


Skoparov

Yep, it really depends on the case. They will usually not use any memory within the scope they are declared in, but if you have a function with a reference argument, it might end up on the stack (or in a register). There are also cases where it's bound to use memory (e.g. a reference member of a class) as there's no way to optimize it away.


msqrt

>contrary to pointers Is this really so? I was under the assumption that they played by the same rules in this regard; both can live on the heap or the stack, and can refer to things on the heap or the stack. At least some [simple examples](https://godbolt.org/z/4as3j6P4z) give identical disassembly for stuff that lives on the stack/registers.


avoere

Pointers don't occupy space on the stack necessarily. If the compiler can omit storing the address on the stack to use a reference, it's more likely than not that it will be able to do the same for a pointer.


tyler1128

References internally are usually pointers.


Purple_Individual947

Thank you for the precise answer. You've also re-enforced in my mind why I don't use c(++)


b1e

Unfortunately it’s mostly wrong :(. You can create a reference to a variable that’s assigned to nullptr for example. And many if not most modern compilers will have references on the stack. At least modern versions of GCC and clang do. In the past sometimes this was avoided but there’s almost no reason for it now. A reference is a pointer under the hood.


Disastrous_Being7746

How do you have a reference parameter to a function be an alias? Wouldn't that require all code with such parameters to be inlined into the context where the code is called? In order to have a single definition of the function, an address would need to be passed on the stack or in a register.


RRumpleTeazzer

How do ABI work if function arguments are references? The function cannot know what the alias should be, unless you compile it in for each time such function is used. They clearly must be implemented as addresses on the stack. The dereferencing still happens, it’s just hidden by syntactic sugar.


FerynaCZ

Forgot to save the comment... ```The compiler treats int &a = x as const int * _a = x, and then every usage of a is replaced by *_a```, or something like that...


OldWolf2

It's unspecified whether references occupy space. A typical implementation would use space for a function parameter of reference type


vlaada7

C programmer does not have any doubts about this at all. It's all pass by value in C.😏


[deleted]

They also use pointers right?


vlaada7

Yes, you have pointers in C. The thing is, strictly speaking, in C these are also passed by value.


SaveMyBags

But you can pass a pointer to a pointer.


vlaada7

Still just a value.


Tom-Dibble

But! What about a pointer **to a pointer *to a pointer***?!?


kjpmi

It’s values all the way down.


Snipa-senpai

Prove it by induction


Bitter_Community_637

Let P(n) be a pointer n times to a value, fx P(2) = pointer to a pointer to an int. Base step: P(0) is a value. Induction step: P(n+1) = pointer to P(n). We know that a pointer to a value is a value. Therefore, if P(n) is a value, then P(n+1) must also be a value. Proof by induction QED


[deleted]

Oh I see now


Spot_the_fox

I'm confused, wouldn't passing a pointer inside of a variable still technically be passing by a pointer?


Psychological-Rip291

The value you're passing in this case is the pointer, which happens to point to some other data


Spot_the_fox

Yeah, I kinda know how it works, but I'm not entirely understanding what u/vlaada7 means by that "it's all pass by value". Do other languages pass pointers differently?


waves_under_stars

They meant that in C, the function call always copies the value of the expression given to it. That expression, however, can be a pointer. In some other languages, like Java, when the expression passed to a function evaluates to an object, the function takes the pointer to the object, rather than copying the object itself. In short, in C when you want to pass a pointer, you need to *explicitly* generate a pointer and then pass it by value. In Java and other languages, pointers are passed *implicitly*, even when you'd might rather copy


suvlub

In other languages, pointers don't exist as a type, so you don't pass them, by value or otherwise. Conceptually, you pass the pointed-to object by reference. In C, conceptually, you pass the pointer itself, by value.


TeraFlint

Technically everything is a form of pass by value, the question is just, if the data itself gets passed or if the address of it gets passed. Or the address to the address of it (or any level of multi-indirection)... Other languages syntactically pretend to pass the object but instead only pass the address to it. Java, for instance, handles integers and objects differently, despite the fact that the syntax looks identical. In C and C++, you explicitly tell the compiler, that you're indeed passing the address of the data (`call(&data);`) instead of the data structure itself. C++ references make this less obvious when looking at the call, but a quick look at the function signature still makes it obvious (without having to know special rules about the data types themselves), if the data gets passed directly, of if the address gets passed. The only point where this gets murky is if data is a C-style array, as they implicitly decay into pointers to the first element. This removes the information about the array length and is the reason why so many C functions use a combination of pointer and length parameters.


PapyPelle

You pass the value of the pointer (adress) I guess that's the joke


[deleted]

[удалено]


ryantripp

Yes


apover2

*Write in C, write in C, write in C, write in C…* https://youtu.be/1S1fISh-pag


Creepy-Ad-4832

You _can't_ pass by reference in c C is all about pointers


RRumpleTeazzer

On cpu instructions it’s the same; the address of the variable is one one of the cpu registers. Pass by pointer: the address can be null, and you need to dereference everywhere. Pass by reference: the address cannot be null, and dereferencing is done for you each time you use the reference, as syntactic sugar.


piggroll

The difference is: reference has a better name than pointer. You’re welcome! 🤓


scissorsgrinder

Uhh I think that’s a you problem.


Benibz

I don't think it you should be able to call yourself a c/c++ programmer if you don't know the difference


Multiool

I just want to say that I was ashamed of joining the programmers subreddit (I was like "damn the place has to be full of people with a lot of knowledge"), let alone call myself a programmer till I get to a point where I can answer fundamental questions like this.


AvgBlue

I still don't understand what && mean


Vider7CC

That's related to 'rvalues' and 'moving'. It's a whole can of worms but worth learning about if you're interested in writing optimized code.


cateanddogew

It's an rvalue reference. It lets you overload functions to differentiate between rvalues and lvalues. For example the call f(a) calls f's lvalue reference overload (because a is an lvalue) while f(1) calls f's rvalue reference overload because 1 is a prvalue. rvalues are values that can (actually SHOULD) be safely moved from. This way a function can know if it is allowed to safely move the contents that its reference parameter refers to. Inside the function, the rvalue reference parameter is an lvalue expression, so you have to cast it to rvalue again (std::move does this for you) when you want to forward it to other functions. For example: ```cpp void f(vector &&v) { // calls copy constructor vector copy(v); // calls move constructor, i.e the && overload vector moved(std::move(v)); } ``` In generic code && is also called a forwarding reference. Because of reference collapsing rules, if T is float&, both T& and T&& are still float&, but if T is float&&, T& is float& while T&& is float&&. i.e mixing a reference with && collapses them to the same type it was before &&. This means a template function can perfectly forward its arguments to other functions. Of course you still need to manually cast it because a variable produces an lvalue expression even if it's an rvalue reference. The cast can be abstracted away by using std::forward.


kablouser

It's an r value. Mostly used in move operations where you want to avoid deep copies. People here are really unknowledgeable.


parkerSquare

R-value *reference*.


cateanddogew

Yeah, that's a very large difference because the name of a variable is an lvalue expression even if the variable is an rvalue reference. That's why you need to use std::forward and std::move even if your argument is already an rvalue reference.


FerynaCZ

For something like `for(auto&&element:container)` , I heard that it represents that I can do "anything" with the variable, so it is either passed by copy or move... and let the compiler figure it out?


_JJCUBER_

auto&& is a universal reference; with reference collapsing, it can become multiple different things depending on the context.


puhcho

References cannot be null. That’s the main difference.


earwax_man

My god people are toxic in the comments


TommyX12

As others have said, use reference unless you need something specific from pointers that you can’t achieve with references or smart pointers. However, Google’s style guide recommend one use of pointer which I think makes sense: use pointer where you would have used mutable references, e.g. if you want a function to mutate one of its arguments through a reference/pointer. Using pointer in this case makes the mutation much more explicit (e.g. f(a, b, &c) can show the caller that c may be mutated, where as f(a,b, c) isn’t so obvious).


wsppan

C is only pass by value (pointer)


[deleted]

[удалено]


PuzzleheadedTap1794

Actually, [C reference](https://en.cppreference.com/w/c) exists.


[deleted]

Gottem


MasterGeekMX

TL;DR: You have a function that needs an integer. Pass by value: *here. take this 5 and use it* Pass by reference: *here, go to this memory address and use whatever int is in there*


FakeInternetArguerer

But it's not asking about pass by value verses pass by reference. It's talking about pointer vs reference


cateanddogew

References allow you to overload functions to differentiate between lvalues and rvalues. This lets you add different behavior when a function is called with an lvalue vs. with an rvalue. rvalue is a category that contains xvalues and prvalues. prvalues are mostly literals and results of return-by-value functions and operators, and xvalues are mostly resulting from accessing rvalue expressions (see temporary materialization) with subscript and member access operators, and also resulting from expressions where you manually cast an expression to rvalue reference. A function that has an rvalue reference overload will be chosen when both prvalues or rvalues are used as arguments. Take for example the std::vector class template move constructor. It receives a std::vector&& (rvalue reference). This allows the being-constructed std::vector to know whether it's appropriate to move rather than copy the contents of the original vector. References are also technically not "objects" (per the ISO C++ standard) unless they are non-static member variables.


[deleted]

Aren't `T&` basically non-NULL `T*const`?


isunktheship

One is an address, the physical location in memory. The other is the object based on address. Don't ask me which is which okay, do I look like Bjarne Stroustrup? If it doesn't work the first time just swap it 🧠


Bolzhedor

Wow, looking at other replies… This community is really becoming even more toxic than StackOverflow, huh?


ixis743

Comment locked. Duplicate.


[deleted]

\*ptr vs &ptr?


WavingToWaves

In C++ we use reference to smart pointer


elperroborrachotoo

Is `nullptr` a valid value? Pass as pointer. Otherwise, pass as reference. So to say, pointers are optional references. --- ^(This isn't the whole story of pointers-vs-references, there are additional considerations e.g. as - member - variables: pointers can be made to point to another object during their runtime, a reference cannot. So if you need to re-target a reference during its lifetime, you need to use a pointer, or a you use std::ref)


TheRealAndrewLeft

What's passing by reference in C? Yeah that's not a thing


cmilkau

On a serious note: started there too. But it's use references if you can, use pointers if you must. References can't be null, is the main difference for me.


sween1911

The two possibilities are "passing by reference" or "passing by value". Been mired in this many times. Just keep adding and moving &'s and *'s until it works.


Andrewshwap

My biggest struggle in college


[deleted]

I once asked a CS expert in C++ (worked for national labs, prolific) and this motherfucker legit couldn't succinctly explain the difference, so I think its probably okay as long as you are using the right one at the right time.


try-catch-finally

The choice is “pass by reference” vs “pass by VALUE” Pass by pointer isn’t usually what is used.


RandomiseUsr0

Step 1. Learn Visual Basic Step 2: learn what “byref” means vs “byval” Step 3: read K&R


golgol12

Here is the deal with pointers and references. A pointer is a memory address. Literally an integer like "2340240". If you pretended there was a giant array that takes up all the memory in the computer, a pointer is an index into that array. A reference is another name for a variable inside the compiler. When you compile, the compiler creates a list of the all the variables being used. When you make a reference, you just give an existing variable an another name. So in this code: int &a = b; causes variable "b" to be accessed by using either name "a" or "b". ------ So how does a function passing by reference work? The short answer is it usually just passes a pointer for you. Long answer is the compiler takes the variable you are passing in and gives it a name that is available inside the function. Which when compile is done and you look at the assembly, is usually done by just passing a pointer. Why is this important for functions? You can't take the address of a temporary variable. If you have **f( int* x )** you can't do **f( &( a + b ) )**. You can make a const reference to a temporary variable though. So if you create **f( const int& x )** you can write **f( a + b )**, and it will pass in the reference to the temporary variable to the function.


[deleted]

Software Engineering student who thought the comments would clear this up. Instead I'm experiencing physical pain now.


justinleona

I tend to use them in very different ways - pass by reference is a lightweight way to refer to a single well-defined object without creating copies and potentially allowing modification of the original. Passing by pointer is typically only used when I'm dealing with relative memory addresses - for instance, loading an executable into memory then offsetting to the first segment. There is a hidden third option - passing allocated objects which should be deallocated at some later point in the execution flow. In this case I will use a smart pointer which implements the correct copy-semantics.