Home  >  Article  >  Backend Development  >  C++ function parameter type conversion rules

C++ function parameter type conversion rules

王林
王林Original
2024-04-13 21:24:02594browse

C Function parameter type conversion rules include: unsigned type conversion to signed type, low-precision type conversion to high-precision type, conversion between floating point types, conversion between compatible pointer types. Practical case: You can pass unsigned integers, low-precision integers and floating-point types as parameters, and the compiler will implicitly convert them to the corresponding types.

C++ 函数参数类型的转换规则

C Function Parameter Type Conversion Rules

In C, a function can be declared to accept parameters of a specific type. If the argument passed to a function is of a different type than the type specified in the function declaration, the compiler attempts to convert the argument to the correct type. This conversion is called implicit type conversion.

Conversion rules

The implicit type conversion rules in C are as follows:

  • Unsigned type conversion to signed type :Unsigned integer types can be converted to signed integer types. For example, unsigned int can be converted to int.
  • Convert low-precision types to high-precision types: Low-precision integer types can be converted to high-precision integer types. For example, short can be converted to int.
  • Conversion between floating point types: Smaller precision floating point types can be converted to larger precision floating point types. For example, float can be converted to double.
  • Conversion between pointer types: Compatible pointer types can be converted to each other. For example, a pointer to a derived class can be converted to a pointer to a base class.

Practical case

The following code demonstrates the use of C function parameter type conversion:

#include <iostream>

void printInteger(int n) {
  std::cout << "Integer: " << n << std::endl;
}

int main() {
  // 传递无符号整数作为参数
  unsigned int ui = 123;
  printInteger(ui);  // 隐式转换为有符号整数

  // 传递精度低的整数作为参数
  short s = 456;
  printInteger(s);  // 隐式转换为有符号整数

  // 传递浮点类型作为参数
  float f = 1.23f;
  printInteger((int)f);  // 显式转换为整数

  return 0;
}

Program output:

Integer: 123
Integer: 456
Integer: 1

The above is the detailed content of C++ function parameter type conversion rules. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn