0

In Python it's possible to format strings conveniently using f-strings:

num = 12
print(f"num is {num}") # prints "num is 12"

Is it possible to do something like this in C? Or something that is similar to that? Currently, to add variables to the output I am using this method:

int num = 12;
printf("num is %d", num);

Is this the only way to add variables to a print statment in C?

imxitiz
  • 3,920
  • 3
  • 9
  • 33
Eladtopaz
  • 1,036
  • 1
  • 6
  • 21

2 Answers2

6
{num}")

Is it possible to do something like this in C?

No, it is not possible. C language is a programming language without reflection. It is not possible to find a variable by its name stored in a string in C.

Python on the other hand is an interpreted language with a whole interpreter implementation behind it that keeps track of all variable names and values and allows to query it within the interpreted language itself. So in python using a string "num" you can find a variable with that name and query its value.

PS. It is possible with many macros and C11 _Generic feature to omit having to specify %d printf format specifier and get C more to C++-ish std::cout << function overloading - for that, you may want to explore my try at it with YIO library. However, for that, it would be advisable to just move to C++ or Rust or other more feature-full programming language.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0

As ForceBru said you can use sprintf(char *str, const char *format, ...), but you need to have an alocated string to receive that result:

int num =0;
char output_string[50];
sprintf(output_string,"num is %d", num);

now output_string can be printed as you want

Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
thiago
  • 103
  • 5
  • I'd suggest using `snprintf()` over `sprintf()`, and of course detecting and handling any errors. – Shawn Aug 21 '21 at 21:07