Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to printf? [closed]

Tags:

c++

printf

printf can be accessed if you #include <stdio.h>. I like using printf because of the format specifiers, and it just feels nicer than doing std::cout << "something\n";.

#include <stdio.h>
#include <cstdlib> // to use rand()

int main() {
    int randNum = rand()%10 + 1;
    printf("Hey, we got %d!\n", randNum);
    return 0;
}

vs

#include <iostream>
#include <cstdlib> // to use rand()
using std::cout;

int main() {
    int randNum = rand()%10 + 1;
    cout << "Hey, we got " << randNum << "!\n";
    return 0;
}

But a user in a discord server that I am in said it was bad practice because "printf is unsafe, use std::cout".

A second user said it was bad because it's not type safe (the first user did mention type safety but not in depth).

The second user said,

Typesafety is enforced by the compiler. However by using a variadic function, the compiler cannot tell the type of the arguments at runtime; it can't know them in advance. The function needs some way to tell what type of arguments to expect, and the printf family of C functions did this through the format string specifiers.

So I'm looking for other alternatives.

If there are none I guess I'll just stick to std::cout

like image 429
incapaz Avatar asked Mar 04 '23 21:03

incapaz


2 Answers

The GNU C++ compiler g++ checks printf arguments at compile-time. If you specify -Wall on the command line, it issues a warning if it detects a mismatch. So if you are using this compiler, you can use printf without worrying.

Your compiler may or may not offer a similar service. But hell, use printf anyway, at least in preference to the ridiculous cout mechanism. Or for a type-safe solution, you might consider using the Boost Format library.

Edited to add: This question has a discussion that you might find interesting.

like image 60
TonyK Avatar answered Mar 15 '23 11:03

TonyK


As an alternative on embedded devices you could consider the <1KB Open Source Trice, which allows printf-like comfort also inside interrupts by delegating the printing task to the external log viewer. I developed this tool, because I found nothing better.

like image 31
Thomas Höhenleitner Avatar answered Mar 15 '23 12:03

Thomas Höhenleitner