I've just started with C and am following along in "The C Programming Language".
In the first chapter I found something that seems quite strange for me (I've done a lot of work in higher level code like JS, Python, C#). What I'm referring to is this snippet that reads input, analyses its length and then copies it if longer than previous:
#include <stdio.h>
#define MAXLINE 1000
int get_line(char line[], int limit);
void copy(char to[], char from[]);
int main () {
int len, max;
char line[MAXLINE], longest[MAXLINE];
max = 0;
while((len = get_line(line, MAXLINE)) > 0) { // <-- here
if (len > max) {
max = len;
copy (longest, line);
}
}
if (max > 0) {
printf("Longest string: %sLength: %d\n", longest, max);
}
return 0;
}
int get_line(char line[], int limit) {
int current, index;
for (index = 0; index < limit -1 && (current = getchar()) != EOF && current != '\n'; ++index)
line[index] = current;
if (current == '\n') {
line[index] = current;
++index;
}
line[index] = '\0';
return index;
}
void copy (char to[], char from[]) {
int index = 0;
while ((to[index] = from[index]) != '\0')
++index;
}
The strange thing in this snippet is how the parameters in the function calls to get_line
and copy
seem to be references (even though they aren't pointers?).
How for instance is line
and longest
values the same in main
as in the helper functions even though main
is missing any scanner and none of the helper functions returns the character arrays.