PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] Why I can pass a number to function which accepts const reference? (C++)

 July 04, 2022     c++, parameter-passing, pass-by-reference     No comments   

Issue

I'm new to C++, while I'm learning pass by reference I realized that I can't create a reference to a number directly, it has to be a variable. But if I define a function which accepts const reference, I can pass numbers in it.

int SumVal(const int& a, int b)
{
    return a + b;
}

As far as I understand, I can pass a number directly like SumVal(1, 2) if the function declared with a const reference because I'll NOT be able to change the reference so the number(or variable) no matter what. The compiler knows this and doesn't complain about it.

But if I define it with normal reference like int SumVal(int& a, int b) I have the chance to change the passed variable inside the function so If I pass a number into this function, the compiler will complain about this.

So I would like to ask that my approach is correct or non-sense.

Thank you for your comments in advance.

(You can also check it out CB Bailey's this answer about pass by reference/value difference)


Solution

Yes. It's because a const reference can bind to an r-value, but normal reference can't



Answered By - justANewb stands with Ukraine
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing