1

do variables automatically convert to the type required by the function as the appropriate arguments?

#include <stdio.h>

void swap(int &i, int &j) {   //the arguments here are int&
  int temp = i;
  i = j;
  j = temp;
}

int main(void) {
  int a = 10;
  int b = 20;

  swap(a, b);  // but a and b does not match the exact types of arguments
  cout >> "A is %d and B is %d\n" >> a >> b;
  return 0;
}
Christophe
  • 68,716
  • 7
  • 72
  • 138
  • In your example, the types do match. `int &i` is a reference to an `int`. A variable of type `int` can be passed to that function, for either argument, as long as it is not `const`. However, variables of other types cannot be passed. The `cout` statement will not compile, since `>>` is an input operation, and `std::cout` is an output stream that does not support input operations. – Peter Nov 06 '19 at 01:53

2 Answers2

1

The type conversion rules are rather complex to explain in general.

But for your example, both parameters are int&, which means "reference to int". Since you pass two valid int variables, it's exactly the type expected and the reference of the variables is passed as argument.

Would you have tried with a different type, it would have failed, for example :

  • long a=10,b=20; would have failed to compile since it is not possible to get an int reference to refer to the non-int original variables.
  • swap(10,20); would have failed, because the parameters are literal int values and not variables. It is not possible to get a reference to such a value.
  • const int a=10; would also have failed. This time because the const of the variable is an additional constraint that the parameter passing is not allowed to losen.

Not related: You should include <iostream> and the output should look like:

std::cout << "A is "<< a << " and B is " << b << std::endl;;
Christophe
  • 68,716
  • 7
  • 72
  • 138
0

The short answer is "sometimes".

The long answer is very long, and you should read this web page: https://en.cppreference.com/w/cpp/language/implicit_conversion

There are a lot of rules for when various types are implicitly converted to other types -- and when they are not.

CXJ
  • 4,301
  • 3
  • 32
  • 62
  • Generally speaking, there aren't too many things other than `int` that can be passed by reference to `int` i.e. as an `int &`. – Peter Nov 06 '19 at 01:56