944,029 Members | Top Members by Rank

Ad:
  • C++ Code Snippet
  • Views: 3118
  • C++ RSS
0

Reference Variable

by on Nov 8th, 2009
What will be the value of "++n" in the above code? Pls help..
C++ Code Snippet (Toggle Plain Text)
  1. int m=5;
  2. int &n=m;
  3. ++n;
Comments on this Code Snippet
Nov 8th, 2009
0

Re: Reference Variable

The vale of n will be 6.
This is because any operation you do on a reference, it also acts on its referenced variable.

Please, if you have a question, don't start a thread as a code snippet, start it as a forum thread. thanx
Posting Whiz in Training
tkud is offline Offline
235 posts
since Sep 2009
Nov 8th, 2009
0

Re: Reference Variable

The absolute easiest way to test this is to write a small console app with those code elements in it and step through the execution and watch what happens to the variable.

If you need a compiler:
http://www.microsoft.com/express
Posting Virtuoso
thines01 is offline Offline
1,691 posts
since Oct 2009
Nov 13th, 2009
0

Re: Reference Variable

but, what's the relation between reference and pointers..?
Newbie Poster
paruse is offline Offline
4 posts
since Oct 2009
Nov 13th, 2009
0

Re: Reference Variable

...a reference is treated the same as the original:
C++ Syntax (Toggle Plain Text)
  1. int main(void)
  2. {
  3. int m=5;
  4. int &n=m;
  5.  
  6. printf("m=%d n=%d\n", m, n); // m=5 n=5
  7.  
  8. ++n; // increments BOTH n and m
  9.  
  10. printf("m=%d n=%d\n", m, n); // m=6 n=6
  11.  
  12. return 0;
  13. }

http://www.cprogramming.com/tutorial/references.html :
C++ references allow you to create a second name for the a variable that you can use to read or modify the original data stored in that variable. While this may not sound appealing at first, what this means is that when you declare a reference and assign it a variable, it will allow you to treat the reference exactly as though it were the original variable for the purpose of accessing and modifying the value of the original variable--even if the second name (the reference) is located within a different scope. This means, for instance, that if you make your function arguments references, and you will effectively have a way to change the original data passed into the function. This is quite different from how C++ normally works, where you have arguments to a function copied into new variables. It also allows you to dramatically reduce the amount of copying that takes place behind the scenes, both with functions and in other areas of C++, like catch clauses.
Posting Virtuoso
thines01 is offline Offline
1,691 posts
since Oct 2009
Message:
Previous Thread in C++ Forum Timeline: Reading from a .csv file.
Next Thread in C++ Forum Timeline: Help with removing file





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC