User Tools

Site Tools


programming:cplusplus:start

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
programming:cplusplus:start [2022/02/28 18:31]
dwheele [Pointers]
programming:cplusplus:start [2022/02/28 18:43] (current)
dwheele [Reference]
Line 68: Line 68:
 ===== Reference ===== ===== Reference =====
  
 +Pointers and references are about the same thing. How we write them is different. References are syntax sugar on top of a pointer.
 +
 +References reference an existing variable.
 +
 +<code c++>
 +int main()
 +{
 +   int a =5;
 +   int& ref = a;// the & is part of the int defintion
 +   // We have created an alias. It is not really a variable.
 +   // We can use ref as though it is "a"
 +   
 +   ref = 2;
 +   std::cout(ref);
 +}
 +// Works, but this is clumsy
 +
 +void Increment (int* value)
 +{
 +   (*value)++;// Value at the pointer "value"
 +}
 +int main()
 +{
 +   // We want to pass the memory address.
 +   int a = 5;
 +   Increment(&a);
 +   LOG(a);
 +}
 +
 +</code>
 +<code c++>
 +// Use a reference instead of a pointer
 +
 +void Increment(int& value)
 +{
 +   value++;
 +}
 +int main()
 +{
 +   int a = 5;
 +   Increment(a);
 +   LOG(a)
 +}
 +
 +</code>
  
  
programming/cplusplus/start.1646073101.txt.gz ยท Last modified: 2022/02/28 18:31 by dwheele