Home  >  Article  >  Backend Development  >  C++ function return values: A quick look at common return code meanings

C++ function return values: A quick look at common return code meanings

王林
王林Original
2024-04-29 17:57:01810browse

The return code of the C function is used to indicate the result of the operation. Common return code meanings include: 0: Operation successful 1: Operation failed -1: Memory allocation failed -2: File opening failed -3: Parameters are incorrect -4: Insufficient resources -5: Invalid pointer

C++ 函数返回值:速查常见的返回码含义

C Function return values: A quick look at the meanings of common return codes

In C, functions are usually passed by their return value information. The return code is an integer that represents the result of the function operation.

The following are some common return code meanings:

Return Code Meaning
0 Operation successful
1 Operation failed
- 1 Memory allocation failed
-2 File opening failed
-3 Incorrect parameters
-4 Insufficient resources
-5 Invalid pointer

Actual case:

#include <iostream>
#include <fstream>

using namespace std;

// 自定义函数,打开文件并读取其第一行
int open_and_read_file(const char* filename) {
  ifstream file(filename);
  if (file.is_open()) {
    string line;
    getline(file, line);
    cout << "读取文件成功,第一行:" << line << endl;
    return 0; // 操作成功
  } else {
    cerr << "文件打开失败" << endl;
    return -2; // 文件打开失败
  }
}

int main() {
  const char* filename = "test.txt";
  int result = open_and_read_file(filename);

  switch (result) {
    case 0:
      cout << "操作成功" << endl;
      break;
    case -2:
      cout << "文件打开失败" << endl;
      break;
    default:
      cout << "未知错误" << endl;
  }

  return 0;
}

Output:

读取文件成功,第一行:这是一个测试文件
操作成功

In this actual case , the open_and_read_file() function returns 0, indicating that the operation is successful, so the switch statement in the main function correctly prints the "operation successful" message.

The above is the detailed content of C++ function return values: A quick look at common return code meanings. 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