-1

suppose i have defined a int x with a value of 10, along with a function int printnumber with required parameters int num.

int printnumber(int num) {/*it will print the number*/ }

I called the function printnumber, passing the variable x as an argument. expected that it will print the value of 10

printnumber(x);

however, it also works if I just passed a raw 10 number as a parameter

printnumber(10);

why is this?

abdo Salm
  • 1,678
  • 4
  • 12
  • 22
  • 4
    You've told the function to expect an `int` as its parameter. Both `10` and `x` (as you've defined it) are `int`s. I'm a bit lost as to what problem you think you see here. – Jerry Coffin Oct 01 '22 at 01:27
  • 3
    Why shouldn't it work? `printnumber` needs an `int` value. You gave it an `int` value. What's wrong with that? It won't work without storage if it needs a *pointer* to an `int` (in which case the pointer must point to somewhere, or be `NULL` and explicitly not pointing anywhere), but it's asking for the raw value, the value need not come from any particular place. – ShadowRanger Oct 01 '22 at 01:27
  • Case #1, the value of x is passed. Case #2, the value 10 is passed. Simple. `printnumber()` receives a value and prints it (or so we are led to believe). btw: is this 'C' or 'C++'??? – Fe2O3 Oct 01 '22 at 01:36
  • Tip: People who know how the programming language works are not going to be surprised by the language working. So if you want to know why something works, you should add an explanation of why you thought it would not work. – JaMiT Oct 01 '22 at 01:42
  • 1
    This is explained in any [beginner c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). These are also available as PDFs for free. – Jason Oct 01 '22 at 05:10
  • Why wouldn't they? Give a good reason. – n. m. could be an AI Oct 01 '22 at 06:48

2 Answers2

1

Because x and 10 are both convertable to int, try to change

int printnumber(int num) {/*it will print the number*/ }

On

int printnumber(int& num) {/*it will print the number*/ }

And see what will change

TheRyuTeam
  • 233
  • 1
  • 6
1

however, it also works if I just passed a raw 10 number as a parameter

Because 10 is an int prvalue and hence it can be used as an argument to a function that has a parameter of type int and takes that argument by value.

On the other hand, if you were to change the parameter to a nonconst lvalue reference, then the call printnumber(10) will no longer works because a prvalue int cannot bind to a nonconst lvalue reference parameter.

This is trivial and is explained in any beginner c++ book.

Jason
  • 36,170
  • 5
  • 26
  • 60