var and &var

"why is the sky blue" question.

If both var and &var are referring to the same memory location, why is var passed to function parameters and handled differently than reference &vars passed the same fx? Why does the former copy its value to another location while the latter is modified at the address of its original variable? What does the processor do to handle &(what does it do at a lower level)?

Sorry this is a bit of a wide open question.
Thanks in advance for answering.
Last edited on
Hi,

A programming language needs to have the ability for a function to work in it's own scope (that is: separate from everything else)- if we didn't have that, then there wouldn't be much point in having functions at all. However, it is also convenient for a function to alter the value of a variable in an outer scope, so there is pass by reference (meaning pointers or actual references) for that purpose. Pass by reference also has the obvious advantage of not copying the whole (large?) variable. Then there is the added protection of const.

Normally with scope, all the variables in any current outer scope are visible, as well the ones in the inner most scope. With a function call, there is a specific local scope for that function, anything outside of that is not available - unless there are parameters which are pointers or references.

How the compiler actually handles scope - I don't know :+) The innards of the compiler is a whole new world ! Perhaps I could speculate that it somehow uses lookup tables: a new scope is a new lookup table? Anything further than that , I don't have a clue.

What does the processor do to handle &(what does it do at a lower level)?


I am sure you already know that a pointer is a variable that holds a memory address, and that & returns the memory address of a variable.

AFAIK, if a function parameter is a pointer type, then the compiler just alters the value at that address. If the parameter is a variable type, then a copy of the value at the variable's address is put into the scope of the function with it's new address.

If the pointer variable is not a function parameter, then one can only do what one can normally do with pointers: dereference them; assign to another pointer variable; and pointer math.

I hope this has been a reasonable attempt to answer your blue sky question :+)
So many questions in one question.Well! let's examine it one by one.

First,thing you must know is a reference is just an alternative name for a variable or object.So it does not have an address of it's own so,if you do something like this

int i , &ri=i ;

cout<< &i << &ri ;

The address is the same.You can find more information on reference here https://corecplusplustutorial.com/cpp-reference/ .

Secondly,passing/receiving a reference is same as passing/receiving an address of the value not the value itself.If an address is passed to the function the compiler will not allocate any extra memory and so any changes made is directly affected to the value present in that address.We can say that the compiler treats passing of reference and pointers indifferently.

Thirdly,if I am not mistaken preprocessor has no role to play on how var and &var are handled it is the compiler that is doing all the tedious work.It's work is just to substitute preprocessor variables with it's value.

regards!
Last edited on
Just to wrap up(maybe) this was some good reading. I already knew a lot of it, but there were some key ideas that helped me:

In this case I always flag a reductionistic explanation:
It's work is just to substitute preprocessor variables with it's value.

Any expansion on that would help very much, even if not overtly related to the subject.

If an address is passed to the function the compiler will not allocate any extra memory and so any changes made is directly affected to the value present in that address.

This was key for me as well - & - will not allocate extra memory.

A very simplified explanation
https://blog.penjee.com/passing-by-value-vs-by-reference-java-graphical/

First,thing you must know is a reference is just an alternative name for a variable or object.


But they are treated differently..

If the pointer variable is not a function parameter, then one can only do what one can normally do with pointers: dereference them; assign to another pointer variable; and pointer math.


Will continue to study pointers vs. ref.

Thank you!!
Last edited on
By preprocessor variables in C++ will mean a type alias given to a variable using define for instance,

#define size 10 ///'size' is the type alias of the value 10

int main()
{
char arr[size] ; ///size gets substituted with the value 10 here

///do something here with arr[]

cin.get() ;
return 0 ;
}

When you run the program the the preprocessor will substitute the value of size as 10 in arr[size] array.So basically preprocessor variables are nothing but a variables that gets substituted with it's value by the preprocessor during compilation of the program.
@Corecplusplus

By preprocessor variables in C++ will mean a type alias given to a variable using define for instance,


I think of #define as being like a substitution operation: in the example, every time the pre-processor see's size it simply substitutes the literal 10 in it's place. I know you mentioned substitution several times, but It has nothing to do with type alias, the type depends on the context. The same thing happens with #include and if one used #define to define a macro.

Note that neither macro definitions, and "variables values" with #define are recommended. With the values, it's better to use a const variable. With macro's, they are often discouraged, perhaps better to have a function or lambda.

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines.html#Res-macros


I had a read of your site. I can see you have already put quite a bit of effort. My main comment though: one has to be very careful about doing this. There are many experts out there, and one becomes open to lots of criticism if there is anything wrong. Realise that you are attempting to produce something that is at least as good as what is already there, and avoid providing something sub-standard. The ones that already provide quality resources usually have tremendous knowledge and experience.

I wonder about your motivation for writing this tutorial. It seems you have read one book and liked it, have seen another which you didn't enjoy so much. Perhaps you feel you can write something that explains things better? But there are many other very good books out there: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list I have heard (from JLBorges )that this book is very good: C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) , a review: http://accu.org/index.php?module=bookreviews&func=search&rid=1848

IMO, your tutorial seems to have a bias towards C. Realise that C++ is quite a different paradigm to C, and requires a different way of thinking. To me, this would have an impact on what topics were mentioned in a tutorial, and when. For example I wouldn't even mention pointers until the topic of polymorphism was discussed.

There are some parts which are misleading if read in isolation. For example you talk about float having 6 significant figures, but the code demonstrates the default of 6 sf for std::cout, and this is not related and nor is the difference made clear. Also, I would advise not to ever show bad practise in the code, as in using floats in equality conditionals, and initialising floats with more precision than they can handle, and using C style casts. I would have preferred an examples of how float's precision can easily be exceeded, and how to do comparisons properly. It would be better to introduce double early, after all it's the default FP type. I prefer to not use float at all, and only if some library requires it, say.

With C style casts, perhaps you explain the loss of precision in a cast without using a C style cast as an example. C style casts are not recommended.

I could probably mention dozens of things, but here are few examples of what I am talking about.

With the section on references, I found that particularly confusing:

C++ reference-what is?

A reference is nothing but another name for a variable so it does not have an address of it’s own.We can make a reference refer to another variable/object.To make variable a reference we add the symbol ‘&‘ in front of the variable name.


.
We can make a reference refer to another variable/object.


Misleading: A reference can only refer to one variable, it's not possible to reseat them. Although I can see how you meant to create a reference to start with. For me, I never need to create a reference directly, they are always indirect as a function parameter.

To make variable a reference we add the symbol ‘&‘ in front of the variable name.


Better and clearer to put & after the type. & before the variable name is easily confused with address of operator.

int i=90 , &ri=i ; ///ri is a reference


Error prone to declare more than one variable in 1 LOC, consider this:

int * ptr, ptr2;

ptr is a pointer to int, ptr2 is just an int - not what was intended or construed from the variable name.

Also, ii is a terrible name for a variable.

With C++, it is better to delay a declaration until one has a sensible value to assign to it. So we have declaration and assignment all in one statement, and this helps with the golden rule of always initialising variables.

*Note the actual address value is represented in hexadecimal format but here it is casted to int type so the address is in integer format.


Everything is represented in binary format, how it might be displayed or what the default format is, is another matter.

With function arguments and parameters:

In such case the programmer has to pass some values such values which is passed when the function is called is known as parameter.And the parameter when received by the function is known as arguments.


I think you have that backwards, my friend :+) Consider these:

1
2
// A function call
int a = AddInt(10, 20); // 10 and 20 are arguments 


1
2
3
// A function declaration
int AddInt(const int Number1, 
          const int Number2); // Number1 and Number2 are parameters 


Pointers:

C++ pointers-what is?

A pointers is a variable that can point to another variable or object.To make variable a pointer we simply add the sign ‘*’ in front of the variable name.


A pointer is a variable that can hold the address of a variable. Place the * after the type Placing it before the variable name is easily confused with dereferencing the pointer. I like to put the * right next to the type (no space) to reinforce the association with the type, not the variable: int* PtrToInt; There have been lots of arguments about this personal preference, but I find it the most logical.

What is the size of a pointer?.Any pointer whether it is of int type or float type or char type the size is always 4 bytes.


That's true for a 32 bit machine, on a 64 bit system (very common now) it's 8 bytes. Btw, sizeof() is very rarely required in C++ (especially with the STL), it is more of a C thing.
Last edited on
I like your criticism and reviews!.When writing this tutorial I had a lot in mind so somethings did not appear as it was supposed to be intended.I'ill update and try to polished my used of words and code and other stuff.

regards!
@Corecplusplus

When writing this tutorial I had a lot in mind so somethings did not appear as it was supposed to be intended.


I have now read all of the material in your tutorial, to be frank IMHO it's worse than "some things" not being right. I have issues with most of it: it's not just the content; but the style and approach as well. Sorry if that sounds harsh, but I am sure there will be others who agree. This is the nature of commenting on such a technical subject as C++ on the internet: if one says something which is incorrect, then there are plenty who will not hesitate in telling one so.

Again, I think it boils down to your motivation for doing this: what is better about your tutorial over the myriad of existing material?
Topic archived. No new replies allowed.