Bulat M. Bulat M. - 1 month ago 8
C Question

How should one structure code when have two branches to branch into

Say, I one writes a daemon.
Has two options and does not know which to choose from:

OPTION 1:

int
main(void)
{
/* Do something with run_as_daemon variable */
if (run_as_daemon) {
pid = fork();
if (pid < 0)
err_exit("Could not fork to create daemon");
if (pid > 0)
exit(0); /* exit if parent */
} else {
do_task(); /* Perform some IO using user commands */
}
}


OPTION 2:

int
main(void)
{
if (run_as_daemon) {
pid = fork();
if (pid < 0)
err_exit("Could not fork to create daemon");
if (pid > 0)
exit(0); /* exit if parent */
}
do_task(); /* Perform some IO using user commands */
}


I understand that they do the same thing but want to know to to better structure code to make it easier to maintain and read.

Answer

Both are applicable in this situation, however the first option creates more readable code in my opinion as you are implying that one of either branches can be taken and that it is not possible to drop down into do_task() if run_as_demon != 0

Comments