Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we call a function inside printf()? [duplicate]

Tags:

c

printf("%d",func(i));

Is this possible in C?

Let us think that func(i) is separate function, can we call it inside printf or scanf?

like image 557
Charan Avatar asked Oct 17 '25 09:10

Charan


1 Answers

Yes. Although it's rather special in some ways, printf is just another function. And a function call can be part of an expression. And the arguments you pass to functions are themselves expressions.

An expression is anything you can compute. So

i + 1

is an expression. But just plain

i

is also a (simpler) expression. And just plain

1

is an even simpler expression.

We build big expressions up out of littler ones. So if expr1 is an expression and expr2 is another expression, then

expr1 + expr2

is a bigger expression that combines them.

Just as you can take two little expressions (sometimes we call these "subexpressions") and combine them to form a larger expression using the + operator, we can also take some expressions and combine them together by calling a function:

f(expr1, expr2)

Now, returning to your question, the call

func(i)

is an expression. But when you call printf, what it expects to see for arguments is

printf(expression, expression, expression, ...)

Now, in printf's case, that first expression must be a string, and it's virtually always a constant string. But the remaining arguments can be anything: 1, i, i + 1, func(1), or just about anything:

printf("%d %d %d %d %d\n", 1, i, i+1, func(i), i+1+func(i));

The only thing to worry about, of course, is that you have as many expressions as additional arguments as you have % signs in the first argument (that is, in the format string), and the types of those additional arguments must match the types expected by the particular format specifiers you have used (%d, %f, %s, etc.).

like image 123
Steve Summit Avatar answered Oct 20 '25 00:10

Steve Summit