Why is `const int& k = i; ++i; ` possible? [duplicate] Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Why can const int& bind to an int?A const & refers to a nonvolatile variable. The variable changes. Does the change invalidate the const &?What is the difference between const and readonly?How to convert a std::string to const char* or char*?Why can templates only be implemented in the header file?Meaning of 'const' last in a function declaration of a class?What is the difference between const int*, const int * const, and int const *?Why is “using namespace std” considered bad practice?define() vs constWhy does ++[[]][+[]]+[+[]] return the string “10”?Why are elementwise additions much faster in separate loops than in a combined loop?Why is it faster to process a sorted array than an unsorted array?

Is this homebrew Lady of Pain warlock patron balanced?

Using audio cues to encourage good posture

Why are both D and D# fitting into my E minor key?

For a new assistant professor in CS, how to build/manage a publication pipeline

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?

Around usage results

また usage in a dictionary

Is it common practice to audition new musicians one-on-one before rehearsing with the entire band?

Wu formula for manifolds with boundary

How to convince students of the implication truth values?

How come Sam didn't become Lord of Horn Hill?

An adverb for when you're not exaggerating

old style "caution" boxes

If my PI received research grants from a company to be able to pay my postdoc salary, did I have a potential conflict interest too?

How do I make this wiring inside cabinet safer? (Pic)

Circuit to "zoom in" on mV fluctuations of a DC signal?

When the Haste spell ends on a creature, do attackers have advantage against that creature?

Crossing US/Canada Border for less than 24 hours

What causes the direction of lightning flashes?

Did MS DOS itself ever use blinking text?

Why aren't air breathing engines used as small first stages

First console to have temporary backward compatibility

Is "Reachable Object" really an NP-complete problem?

How do pianists reach extremely loud dynamics?



Why is `const int& k = i; ++i; ` possible? [duplicate]



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Why can const int& bind to an int?A const & refers to a nonvolatile variable. The variable changes. Does the change invalidate the const &?What is the difference between const and readonly?How to convert a std::string to const char* or char*?Why can templates only be implemented in the header file?Meaning of 'const' last in a function declaration of a class?What is the difference between const int*, const int * const, and int const *?Why is “using namespace std” considered bad practice?define() vs constWhy does ++[[]][+[]]+[+[]] return the string “10”?Why are elementwise additions much faster in separate loops than in a combined loop?Why is it faster to process a sorted array than an unsorted array?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








13
















This question already has an answer here:



  • Why can const int& bind to an int?

    8 answers



  • A const & refers to a nonvolatile variable. The variable changes. Does the change invalidate the const &?

    4 answers



I am supposed to determine whether this function is syntactically correct:



int f3(int i, int j) const int& k=i; ++i; return k;



I have tested it out and it compiles with my main function.



I do not understand why this is so.



Surely by calling the function f3 I create copies of the variables iand j in a new memory space and setting const int& k=i I am setting the memory space of the newly created k to the exact the same space of the memory space of the copied i, therefore any change, i.e. the increment ++iwill result in ++k which is not possible given that it was set const



Any help is greatly appreciated










share|improve this question













marked as duplicate by Cody Gray c++
Users with the  c++ badge can single-handedly close c++ questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 27 at 7:13


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 2





    Small nitpicking: int f3(int i, int j) const int& k=i; ++k; return k; would be syntactically correct too

    – danielspaniol
    Mar 27 at 6:37











  • @danielspaniol I get error: cannot assign to variable 'k' with const-qualified type 'const int &'

    – Thomas Sablik
    Mar 27 at 10:38






  • 1





    @ThomasSablik That is a semantical error. The syntax is correct.

    – danielspaniol
    Mar 27 at 10:44











  • I am setting the memory space of the newly created k. No. K is a reference, this means is equivalent to an alias (an alias is literally another another name for a variable). So k does not need its own variable it is simply another name for i (though it is const qualified). You can verify that it does not have its own memory because you can not take the address of k, if you try you will get the address of i.

    – Martin York
    Mar 28 at 17:31












  • @MartinYork If you put int &k in a struct A, make it the first field, take address of the struct, and cast it from A* to int**: you will have the address of the int &k.

    – atomsymbol
    Apr 3 at 22:18

















13
















This question already has an answer here:



  • Why can const int& bind to an int?

    8 answers



  • A const & refers to a nonvolatile variable. The variable changes. Does the change invalidate the const &?

    4 answers



I am supposed to determine whether this function is syntactically correct:



int f3(int i, int j) const int& k=i; ++i; return k;



I have tested it out and it compiles with my main function.



I do not understand why this is so.



Surely by calling the function f3 I create copies of the variables iand j in a new memory space and setting const int& k=i I am setting the memory space of the newly created k to the exact the same space of the memory space of the copied i, therefore any change, i.e. the increment ++iwill result in ++k which is not possible given that it was set const



Any help is greatly appreciated










share|improve this question













marked as duplicate by Cody Gray c++
Users with the  c++ badge can single-handedly close c++ questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 27 at 7:13


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 2





    Small nitpicking: int f3(int i, int j) const int& k=i; ++k; return k; would be syntactically correct too

    – danielspaniol
    Mar 27 at 6:37











  • @danielspaniol I get error: cannot assign to variable 'k' with const-qualified type 'const int &'

    – Thomas Sablik
    Mar 27 at 10:38






  • 1





    @ThomasSablik That is a semantical error. The syntax is correct.

    – danielspaniol
    Mar 27 at 10:44











  • I am setting the memory space of the newly created k. No. K is a reference, this means is equivalent to an alias (an alias is literally another another name for a variable). So k does not need its own variable it is simply another name for i (though it is const qualified). You can verify that it does not have its own memory because you can not take the address of k, if you try you will get the address of i.

    – Martin York
    Mar 28 at 17:31












  • @MartinYork If you put int &k in a struct A, make it the first field, take address of the struct, and cast it from A* to int**: you will have the address of the int &k.

    – atomsymbol
    Apr 3 at 22:18













13












13








13


1







This question already has an answer here:



  • Why can const int& bind to an int?

    8 answers



  • A const & refers to a nonvolatile variable. The variable changes. Does the change invalidate the const &?

    4 answers



I am supposed to determine whether this function is syntactically correct:



int f3(int i, int j) const int& k=i; ++i; return k;



I have tested it out and it compiles with my main function.



I do not understand why this is so.



Surely by calling the function f3 I create copies of the variables iand j in a new memory space and setting const int& k=i I am setting the memory space of the newly created k to the exact the same space of the memory space of the copied i, therefore any change, i.e. the increment ++iwill result in ++k which is not possible given that it was set const



Any help is greatly appreciated










share|improve this question















This question already has an answer here:



  • Why can const int& bind to an int?

    8 answers



  • A const & refers to a nonvolatile variable. The variable changes. Does the change invalidate the const &?

    4 answers



I am supposed to determine whether this function is syntactically correct:



int f3(int i, int j) const int& k=i; ++i; return k;



I have tested it out and it compiles with my main function.



I do not understand why this is so.



Surely by calling the function f3 I create copies of the variables iand j in a new memory space and setting const int& k=i I am setting the memory space of the newly created k to the exact the same space of the memory space of the copied i, therefore any change, i.e. the increment ++iwill result in ++k which is not possible given that it was set const



Any help is greatly appreciated





This question already has an answer here:



  • Why can const int& bind to an int?

    8 answers



  • A const & refers to a nonvolatile variable. The variable changes. Does the change invalidate the const &?

    4 answers







c++ syntax reference const






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 22:27









user9078057user9078057

1469




1469




marked as duplicate by Cody Gray c++
Users with the  c++ badge can single-handedly close c++ questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 27 at 7:13


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Cody Gray c++
Users with the  c++ badge can single-handedly close c++ questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 27 at 7:13


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 2





    Small nitpicking: int f3(int i, int j) const int& k=i; ++k; return k; would be syntactically correct too

    – danielspaniol
    Mar 27 at 6:37











  • @danielspaniol I get error: cannot assign to variable 'k' with const-qualified type 'const int &'

    – Thomas Sablik
    Mar 27 at 10:38






  • 1





    @ThomasSablik That is a semantical error. The syntax is correct.

    – danielspaniol
    Mar 27 at 10:44











  • I am setting the memory space of the newly created k. No. K is a reference, this means is equivalent to an alias (an alias is literally another another name for a variable). So k does not need its own variable it is simply another name for i (though it is const qualified). You can verify that it does not have its own memory because you can not take the address of k, if you try you will get the address of i.

    – Martin York
    Mar 28 at 17:31












  • @MartinYork If you put int &k in a struct A, make it the first field, take address of the struct, and cast it from A* to int**: you will have the address of the int &k.

    – atomsymbol
    Apr 3 at 22:18












  • 2





    Small nitpicking: int f3(int i, int j) const int& k=i; ++k; return k; would be syntactically correct too

    – danielspaniol
    Mar 27 at 6:37











  • @danielspaniol I get error: cannot assign to variable 'k' with const-qualified type 'const int &'

    – Thomas Sablik
    Mar 27 at 10:38






  • 1





    @ThomasSablik That is a semantical error. The syntax is correct.

    – danielspaniol
    Mar 27 at 10:44











  • I am setting the memory space of the newly created k. No. K is a reference, this means is equivalent to an alias (an alias is literally another another name for a variable). So k does not need its own variable it is simply another name for i (though it is const qualified). You can verify that it does not have its own memory because you can not take the address of k, if you try you will get the address of i.

    – Martin York
    Mar 28 at 17:31












  • @MartinYork If you put int &k in a struct A, make it the first field, take address of the struct, and cast it from A* to int**: you will have the address of the int &k.

    – atomsymbol
    Apr 3 at 22:18







2




2





Small nitpicking: int f3(int i, int j) const int& k=i; ++k; return k; would be syntactically correct too

– danielspaniol
Mar 27 at 6:37





Small nitpicking: int f3(int i, int j) const int& k=i; ++k; return k; would be syntactically correct too

– danielspaniol
Mar 27 at 6:37













@danielspaniol I get error: cannot assign to variable 'k' with const-qualified type 'const int &'

– Thomas Sablik
Mar 27 at 10:38





@danielspaniol I get error: cannot assign to variable 'k' with const-qualified type 'const int &'

– Thomas Sablik
Mar 27 at 10:38




1




1





@ThomasSablik That is a semantical error. The syntax is correct.

– danielspaniol
Mar 27 at 10:44





@ThomasSablik That is a semantical error. The syntax is correct.

– danielspaniol
Mar 27 at 10:44













I am setting the memory space of the newly created k. No. K is a reference, this means is equivalent to an alias (an alias is literally another another name for a variable). So k does not need its own variable it is simply another name for i (though it is const qualified). You can verify that it does not have its own memory because you can not take the address of k, if you try you will get the address of i.

– Martin York
Mar 28 at 17:31






I am setting the memory space of the newly created k. No. K is a reference, this means is equivalent to an alias (an alias is literally another another name for a variable). So k does not need its own variable it is simply another name for i (though it is const qualified). You can verify that it does not have its own memory because you can not take the address of k, if you try you will get the address of i.

– Martin York
Mar 28 at 17:31














@MartinYork If you put int &k in a struct A, make it the first field, take address of the struct, and cast it from A* to int**: you will have the address of the int &k.

– atomsymbol
Apr 3 at 22:18





@MartinYork If you put int &k in a struct A, make it the first field, take address of the struct, and cast it from A* to int**: you will have the address of the int &k.

– atomsymbol
Apr 3 at 22:18












1 Answer
1






active

oldest

votes


















27















the increment ++i will result in ++k which is not possible given that it was set const




That's a misunderstanding.



You may not change the value of the object through k but it can still be changed through other means. In other words, ++k is not allowed but ++i is still allowed, which will indirectly modify the value of k.



Here's an analogy from a non-computer world.



You may look through the window of a store and see what's inside but you won't be able to change what's inside the store. However, an employee, who is inside the store, can change the contents of the store. You will see that change from
outside. You have const access or view access to the store while the employee has non-const access or change access to the store.






share|improve this answer




















  • 9





    Not so far-fetched. That's a good analogy.

    – user4581301
    Mar 26 at 22:44






  • 1





    Note that this is so because i itself is not const. So we have a const reference a non-const object. Const objects are different.

    – David Schwartz
    Mar 26 at 22:53











  • @DavidSchwartz This is true, but now that I think of it, it doesn't suit the logic for pointers, does it? since const int * would be a non-constant pointer to a constant int and int * const would be a constant pointer to a non-constant int, this should be int & const, shouldn't it? I feel like this is inconsistent.

    – Max
    Mar 27 at 8:52

















1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









27















the increment ++i will result in ++k which is not possible given that it was set const




That's a misunderstanding.



You may not change the value of the object through k but it can still be changed through other means. In other words, ++k is not allowed but ++i is still allowed, which will indirectly modify the value of k.



Here's an analogy from a non-computer world.



You may look through the window of a store and see what's inside but you won't be able to change what's inside the store. However, an employee, who is inside the store, can change the contents of the store. You will see that change from
outside. You have const access or view access to the store while the employee has non-const access or change access to the store.






share|improve this answer




















  • 9





    Not so far-fetched. That's a good analogy.

    – user4581301
    Mar 26 at 22:44






  • 1





    Note that this is so because i itself is not const. So we have a const reference a non-const object. Const objects are different.

    – David Schwartz
    Mar 26 at 22:53











  • @DavidSchwartz This is true, but now that I think of it, it doesn't suit the logic for pointers, does it? since const int * would be a non-constant pointer to a constant int and int * const would be a constant pointer to a non-constant int, this should be int & const, shouldn't it? I feel like this is inconsistent.

    – Max
    Mar 27 at 8:52















27















the increment ++i will result in ++k which is not possible given that it was set const




That's a misunderstanding.



You may not change the value of the object through k but it can still be changed through other means. In other words, ++k is not allowed but ++i is still allowed, which will indirectly modify the value of k.



Here's an analogy from a non-computer world.



You may look through the window of a store and see what's inside but you won't be able to change what's inside the store. However, an employee, who is inside the store, can change the contents of the store. You will see that change from
outside. You have const access or view access to the store while the employee has non-const access or change access to the store.






share|improve this answer




















  • 9





    Not so far-fetched. That's a good analogy.

    – user4581301
    Mar 26 at 22:44






  • 1





    Note that this is so because i itself is not const. So we have a const reference a non-const object. Const objects are different.

    – David Schwartz
    Mar 26 at 22:53











  • @DavidSchwartz This is true, but now that I think of it, it doesn't suit the logic for pointers, does it? since const int * would be a non-constant pointer to a constant int and int * const would be a constant pointer to a non-constant int, this should be int & const, shouldn't it? I feel like this is inconsistent.

    – Max
    Mar 27 at 8:52













27












27








27








the increment ++i will result in ++k which is not possible given that it was set const




That's a misunderstanding.



You may not change the value of the object through k but it can still be changed through other means. In other words, ++k is not allowed but ++i is still allowed, which will indirectly modify the value of k.



Here's an analogy from a non-computer world.



You may look through the window of a store and see what's inside but you won't be able to change what's inside the store. However, an employee, who is inside the store, can change the contents of the store. You will see that change from
outside. You have const access or view access to the store while the employee has non-const access or change access to the store.






share|improve this answer
















the increment ++i will result in ++k which is not possible given that it was set const




That's a misunderstanding.



You may not change the value of the object through k but it can still be changed through other means. In other words, ++k is not allowed but ++i is still allowed, which will indirectly modify the value of k.



Here's an analogy from a non-computer world.



You may look through the window of a store and see what's inside but you won't be able to change what's inside the store. However, an employee, who is inside the store, can change the contents of the store. You will see that change from
outside. You have const access or view access to the store while the employee has non-const access or change access to the store.







share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 3 at 7:22









El Profesor

11k32341




11k32341










answered Mar 26 at 22:31









R SahuR Sahu

171k1298197




171k1298197







  • 9





    Not so far-fetched. That's a good analogy.

    – user4581301
    Mar 26 at 22:44






  • 1





    Note that this is so because i itself is not const. So we have a const reference a non-const object. Const objects are different.

    – David Schwartz
    Mar 26 at 22:53











  • @DavidSchwartz This is true, but now that I think of it, it doesn't suit the logic for pointers, does it? since const int * would be a non-constant pointer to a constant int and int * const would be a constant pointer to a non-constant int, this should be int & const, shouldn't it? I feel like this is inconsistent.

    – Max
    Mar 27 at 8:52












  • 9





    Not so far-fetched. That's a good analogy.

    – user4581301
    Mar 26 at 22:44






  • 1





    Note that this is so because i itself is not const. So we have a const reference a non-const object. Const objects are different.

    – David Schwartz
    Mar 26 at 22:53











  • @DavidSchwartz This is true, but now that I think of it, it doesn't suit the logic for pointers, does it? since const int * would be a non-constant pointer to a constant int and int * const would be a constant pointer to a non-constant int, this should be int & const, shouldn't it? I feel like this is inconsistent.

    – Max
    Mar 27 at 8:52







9




9





Not so far-fetched. That's a good analogy.

– user4581301
Mar 26 at 22:44





Not so far-fetched. That's a good analogy.

– user4581301
Mar 26 at 22:44




1




1





Note that this is so because i itself is not const. So we have a const reference a non-const object. Const objects are different.

– David Schwartz
Mar 26 at 22:53





Note that this is so because i itself is not const. So we have a const reference a non-const object. Const objects are different.

– David Schwartz
Mar 26 at 22:53













@DavidSchwartz This is true, but now that I think of it, it doesn't suit the logic for pointers, does it? since const int * would be a non-constant pointer to a constant int and int * const would be a constant pointer to a non-constant int, this should be int & const, shouldn't it? I feel like this is inconsistent.

– Max
Mar 27 at 8:52





@DavidSchwartz This is true, but now that I think of it, it doesn't suit the logic for pointers, does it? since const int * would be a non-constant pointer to a constant int and int * const would be a constant pointer to a non-constant int, this should be int & const, shouldn't it? I feel like this is inconsistent.

– Max
Mar 27 at 8:52





Popular posts from this blog

How should I support this large drywall patch? Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?How do I cover large gaps in drywall?How do I keep drywall around a patch from crumbling?Can I glue a second layer of drywall?How to patch long strip on drywall?Large drywall patch: how to avoid bulging seams?Drywall Mesh Patch vs. Bulge? To remove or not to remove?How to fix this drywall job?Prep drywall before backsplashWhat's the best way to fix this horrible drywall patch job?Drywall patching using 3M Patch Plus Primer

random experiment with two different functions on unit interval Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)Random variable and probability space notionsRandom Walk with EdgesFinding functions where the increase over a random interval is Poisson distributedNumber of days until dayCan an observed event in fact be of zero probability?Unit random processmodels of coins and uniform distributionHow to get the number of successes given $n$ trials , probability $P$ and a random variable $X$Absorbing Markov chain in a computer. Is “almost every” turned into always convergence in computer executions?Stopped random walk is not uniformly integrable

Lowndes Grove History Architecture References Navigation menu32°48′6″N 79°57′58″W / 32.80167°N 79.96611°W / 32.80167; -79.9661132°48′6″N 79°57′58″W / 32.80167°N 79.96611°W / 32.80167; -79.9661178002500"National Register Information System"Historic houses of South Carolina"Lowndes Grove""+32° 48' 6.00", −79° 57' 58.00""Lowndes Grove, Charleston County (260 St. Margaret St., Charleston)""Lowndes Grove"The Charleston ExpositionIt Happened in South Carolina"Lowndes Grove (House), Saint Margaret Street & Sixth Avenue, Charleston, Charleston County, SC(Photographs)"Plantations of the Carolina Low Countrye