Search code examples
cf-string

Is it possible to format strings in C like Python's f-strings?


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?


Solution

  • {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.