I am trying to learn the basics of C using The C Programming Language - Brian Kernighan and Dennis Ritchie
In the program below, I don't understand where the value for 'maxlineLength
' comes from?
The for loop is set to run while 'i
' is smaller than maxLineLength-1
, but what is the value of maxLineLength
and where does it come from?
From what I understand, when parameters are declared in a function like this a value is being passed to them, so they must surely be declared somewhere else to have the value passed in?
#include <stdio.h>
#define MAXIMUMLINELENGTH 1000
#define LONGLINE 20
main() {
int stringLength;
char line[MAXIMUMLINELENGTH];
while((stringLength = getLineLength(line, MAXIMUMLINELENGTH)) > 0)
if(stringLength < LONGLINE){
printf("The line was under the minimum length\n");
}
else if (stringLength > LONGLINE){
printf("%s", line);
}
return 0;
}
int getLineLength(char line[], int maxLineLength){
int i, c;
for(i = 0; i< maxLineLength-1 && ((c = getchar())!= EOF) && c != '\n'; i++)
line[i] = c;
if(c == '\n') {
line[i] = c;
i++;
}
line[i] = '\0';
return i;
}
From what I understand, when parameters are declared in a function like this a value is being passed to them, so they must surely be declared somewhere else to have the value passed in?
In this case, the function is being declared and defined at the same time. Pre-ANSI C allowed that. This is considered a bad practice today. You should add a forward declaration
int getLineLength(char line[], int maxLineLength);
above main
in order to avoid declaring the function implicitly.
When this forward declaration is missing, the first use of the function becomes its implicit declaration. The compiler takes types of the expression parameters that you pass, and assumes that the function takes corresponding types as its parameters. It also assumes that the function returns an int
. In this case the compiler has all the information necessary to figure out the correct signature, so the function is defined correctly. However, in more complex cases (say, if maxLineLength
was declared as long long
, not int
) it would lead to undefined behavior, so you should always include a forward declaration of your functions.
getLineLength(line, MAXIMUMLINELENGTH)
MAXLINELENGTH
is defined constant
Inside function getLineLength
is this value "mapped" to maxLineLength
variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With