It will make no difference which one you chose if you're using a modern compiler[1]. Take for example the following C code.
#include <stdlib.h>
#include <stdio.h>
void foo(void) {
putchar('\n');
}
void bar(void) {
printf("\n");
}
When compiled with gcc -O1 (optimizations enabled), we get the following (identical) machine code in both foo and bar:
movl $10, %edi
popq %rbp
jmp _putchar ## TAILCALL
Both foo and bar end up calling putchar('\n'). In other words, modern C compilers are smart enough to optimize printf calls very efficiently. Just use whichever one you think is more clear and readable.
- I do not consider MS's
clto be a modern compiler.
It will make no difference which one you chose if you're using a modern compiler[1]. Take for example the following C code.
#include <stdlib.h>
#include <stdio.h>
void foo(void) {
putchar('\n');
}
void bar(void) {
printf("\n");
}
When compiled with gcc -O1 (optimizations enabled), we get the following (identical) machine code in both foo and bar:
movl $10, %edi
popq %rbp
jmp _putchar ## TAILCALL
Both foo and bar end up calling putchar('\n'). In other words, modern C compilers are smart enough to optimize printf calls very efficiently. Just use whichever one you think is more clear and readable.
- I do not consider MS's
clto be a modern compiler.
Are there any best practices for using one over the other?
Let style drive the decision.
Since efficiency of execution is the same or nearly identical, use the style that best conveys the larger code's function.
If the function had lots of printf(), stay with printf("\n").
Likewise for putchar('\n') and puts("")
A good compiler will emit the same efficient code for both putchar('\n'); and puts(""); (when return value not used).
Videos
sorry, im new to programming and im just in the second lecture of cs50.
when write printf("smth\n"); in here, what role \n is playing?