Elements of style (C-version)

Vassilios Karakoidas
2 min readJul 2, 2024

Today i was writing a benchmarking application in C to test the speed of the POSIX regular expression library implementation. I was writing the following while loop …

while(fgets(line,BUF_SIZE,data) != NULL) {
// split the line
int index = indexOf(line,'\t');
int len = strlen(line);
int i = 0;

line_r = substring(line,0,index);
line_s = substring(line,index + 1,len - 1);

if(regcomp(regex,line_r,REG_EXTENDED) != 0) {
printf("Compile Failed for %s\n",line_r);
free(line_r);
free(line_s);
continue;
}

[... other code here ...]

free(line_r);
free(line_s);
}

… and thinking what is more appropriate to do … leave the code like that, duplicating the free functions of line_r and line_s, or using a label with a goto statement to the end of the loop … ending with something like:

while(fgets(line,BUF_SIZE,data) != NULL) {
// split the line
int index = indexOf(line,'\t');
int len = strlen(line);
int i = 0;

line_r = substring(line,0,index);
line_s = substring(line,index + 1,len - 1);

if(regcomp(regex,line_r,REG_EXTENDED) != 0) {
printf("Compile Failed for %s\n",line_r);
goto free;
}

[... other code here ...]

free:
free(line_r);
free(line_s);

}

Note: The substring allocates the buffer (i know that actually is bad policy) and i could do it avoiding the allocation for each line by using two big buffers (i have constant BUF_SIZE). Imagine that buf_size was variable and all buffers have to be allocated each time.

You might be interested to take a look at Go To Statement Considered Harmful by Edsger W. Dijkstra.

--

--

Vassilios Karakoidas

Software Engineer, Software Architect, Researcher. Opinions are my own.