return 2 在 C 中是什么意思?以及关于 bool 和 void 的其他问题。 CS50 Pset 3 复数

What does return 2 mean in C? And additional questions on bool and void. CS50 Pset 3 Plurality

目前正在做 CS50 Pset3 复数练习并查看给定的代码。我想知道 return 2 在代码中是什么意思。

一些补充问题-

为什么是 bool vote(string name);无效 print_winner(无效);不在 int main (int argc, string arg[]) 的大括号内?不明白为什么要这样写,我想了解一下这背后的原因。

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i].name, name) == 0)
        {
            candidates[i].votes++;
            return true;
        }

    }

    // TODO
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    int maxvote = 0;

    for (int i = 0; i < candidate_count; i++)
    {
        if (maxvote < candidates[i].votes)
        {
            maxvote = candidates[i].votes;
        }
    }

    for (int i = 0; i < candidate_count; i++)
    {

        if (candidates[i].votes == maxvote)
        {
            printf("%s\n", candidates[i].name);
        }
    }

    // TODO
    return;
}

main() 函数中的

return 2 表示程序将以退出代码 2 退出,表示错误(任何非零通常被认为是错误)。程序设置如下:

  • 退出代码 0 表示成功(或者它应该,无论如何。该程序在 main() 末尾缺少 return 0
  • 退出代码 1 表示未指定参数
  • 退出代码2表示candidate_count大于最大值

Return 代码在程序中没有意义。但是,当程序实际上是 运行 时,父进程(通常是 shell,例如 Bash)可以解释 return 代码以收集有关进程的有意义的信息'状态。

这些

bool vote(string name);
void print_winner(void);

是函数声明,允许在它们之后编写的代码调用具有给定签名的函数。定义在代码后面;在 C 中,函数定义不需要与声明在同一个文件中,只要函数可以在 link 时找到即可。