Home > database >  why functions still work if i passed a non-variable arguments
why functions still work if i passed a non-variable arguments

Time:10-01

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related