C语言 尝试用const替换#define确实有效



所以我最初使用#define编写程序,因为我知道它是作为预处理器发生的,但是我的老师评论说我应该使用const。我试着在我的代码中替换#define,但它只是打破了它,我不知道为什么。我知道const可以像变量一样使用所以我的代码应该调用它并得到相同的结果,不是吗?这里是我的代码工作和不工作的截图下面是工作:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
//Set constant.Preprocessor for speed repace LENGTH
//With what ever number of digits you would want.
#define LENGTH 4
//Converts the input number into an array of digits
int * digitArray(int number) {
//Creating an array for all digits of the constant length
static int digits[LENGTH];
//Loop through the digits and use the mod operator to get each one of them
for(int i = LENGTH-1; i >= 0; i--) {
digits[i] = number % 10;
number = number / 10;
}
//Finally, return the array pointer
return digits;
}
//Compares the correct number array with the guess array of digits, checking for fermi/pica hints and returns
//the number of exact matches of both arrays
int checkGuess(int *num, int *guess) {
//Create two bool arrays to flag the digits already used
bool usedNum[LENGTH] = {false};
bool usedGuess[LENGTH] = {false};
//First loop to check for number of matches
int matches = 0;
int used = 0;
for(int i = 0; i < LENGTH; i++) {
//Check if the digit is the same for both arrays at i index
if(num[i] == guess[i]) {
//If so there is an exact match
usedNum[i] = true;
usedGuess[i] = true;
matches++;
used++;
}
}

和不工作:

const int LENGTH = 4;
//Converts the input number into an array of digits
int * digitArray(int number) {
//Creating an array for all digits of the constant length
static int digits[LENGTH];
//Loop through the digits and use the mod operator to get each one of them
for(int i = LENGTH-1; i >= 0; i--) {
digits[i] = number % 10;
number = number / 10;
}
//Finally, return the array pointer
return digits;
}
//Compares the correct number array with the guess array of digits, checking for fermi/pica hints and returns
//the number of exact matches of both arrays
int checkGuess(int *num, int *guess) {
//Create two bool arrays to flag the digits already used
bool usedNum[LENGTH] = {false};
bool usedGuess[LENGTH] = {false};
//First loop to check for number of matches
int matches = 0;
int used = 0;
for(int i = 0; i < LENGTH; i++) {
//Check if the digit is the same for both arrays at i index
if(num[i] == guess[i]) {
//If so there is an exact match
usedNum[i] = true;
usedGuess[i] = true;
matches++;
used++;
}
}

我知道这是一种重复的其他一些问题,但我没有看到任何答案,具体说明为什么它不能在这种情况下工作,以及如何修复它,使代码运行。

第二个代码段没有使用编译时已知的常量值,注意const并不真正意味着常量,而是"只读";在c .

从开关

const int LENGTH = 4;

enum { LENGTH = 4 };  // A real constant

,它应该工作。

或者您可以保留它并使用C99或C11进行编译,那么这些数组将是可变长度数组(VLA)(请注意,VLA在C11中是可选的)。但是,当你事先知道元素的数量时,总是首选第一个选项。

:

static int digits[LENGTH];

由于数组总是在循环中填充,因此不需要static关键字。

相关内容

  • 没有找到相关文章

最新更新