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

This question already has answers here:
Calling another function from printf?
(2 answers)
Closed 5 years ago.
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?

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.).

#include<stdio.h>
int sum(int ,int );
void main()
{
int num1,num2;
printf("Enter two numbers: ");
scanf("%d %d",&num1,&num2);
printf("Sum of %d and %d is: %d",num1,num2,sum(num1,num2)); //function call in print statement
}
int sum(int num1,int num2) //function to add two numbers``
{
int result;
result=num1+num2;
return result;
}

Related

why the output in the terminal is different when i put Prefix -- and a-1

#include <stdio.h>
int sum(int a);
int main()
{
int a;
printf("Enter a value: ");
scanf("%d", &a);
printf("%d", sum(a));
return 0;
}
int sum(int a)
{
if (a == 1)
{
return 1;
}
return a + sum(a - 1);
}
When the input is 5 the output is 15 (which is right),
but when the return is, return a + sum(--a);
(for the same input 5) the output is 11
The behaviour of a + sum(--a) is undefined. The compiler has a lot of freedom as to when and how often it reads a, and when and how often it modifies a. Avoid both reading and modifying the same variable in an expression.
When you wrote
a + sum(a - 1)
, a rough translation of that C code into English is:
"Take a plus the result of the sum function applied to the quantity a-1."
That makes sense, and it's just what you want.
If, on the other hand, you write
a + sum(--a)
, now what you're saying is,
"Take a plus the result of the sum function applied to, hang on a minute, I want to take the variable a minus 1 and assign it back to a and then, where was I, pass it to sum()."
Is that really what you want to do? Why would you want to modify a's value in the middle of calling sum()? You wouldn't want to do that, you don't need to do that, that has nothing to do with the problem of calling sum(a - 1). So don't write it that way. It's confusing to you and me, and what's worse, it's so confusing that the compiler can't figure it out, either. It's so confusing that it's undefined behavior, meaning that the compiler isn't even required to figure out what you mean, and the compiler is explicitly allowed to fall back and punt, and compile your program into something that doesn't work — which is precisely what you discovered when you tried it.
See the canonical SO question Why are these constructs using pre and post-increment undefined behavior? for much (much!) more on undefined expressions like these.

Is it possible to pass two arguments in c? [duplicate]

This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 3 years ago.
I have written a C program where I declared a function reverse(int i). When I compile and run the program, it runs fine despite passing two arguments like this reverse((i++, i)). Why doesn't this cause a syntax error? reverse expects one argument.
#include <stdio.h>
void reverse(int i);
int main()
{
reverse(1);
}
void reverse(int i)
{
if (i > 5)
return ;
printf("%d ", i);
return reverse((i++, i));
}
You're not passing two arguments - that would be reverse(i++, i) (which incidentally would invoke undefined behaviour because of the lack of a sequence point between (i++ and i).
You're passing (i++, i) as a single argument. Since it is inside an additional pair of parentheses, the comma here does not separate the arguments of the function, but rather acts as the comma operator.
(i++, i) seems to execute i++, then evaluate to i, the last operand to ,. You can see that here:
// Notice the ( , )
int i = (puts("Inside\n"), 2); // Prints "Inside"
printf("%d\n", i); // Prints 2
It didn't cause an error because you only passed one argument. That one argument though was a sequence of effects that evaluated to i.

What does the [x,y] symbol mean in a multidimensional array access? [duplicate]

This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 3 years ago.
I'm studying C and I came across the code below. The printed results are always the same for all the printf calls.
What does [x,y] mean?
A memory address or something else?
printf("%d ", array[0,0]);
printf("%d ", array[1,0]);
printf("%d ", array[2,0]);
The comma operator in c returns the second argument. So 0,0, 1,0, and 2,0 all evaluate to 0, so its no wonder that all the printf statements print the same result. If you want to refer to an element in a two-dimensional array by its indexes, you need to use two sets of square bracket. E.g., array[1][0].
It's a 'comma operator'. In C, a comma operator evaluates each argument but returns the rightmost argument. So array[0,1] is as same as array[1] and array[0,1,2]is as same as array[2]. In your case array[0,0]), array[1,0], array[2,0] all evaluate array[0]. So all the statements print the same result.
Additionally (from #chqrlie's comment), though it returns the rightmost argument, all the expressions are evaluated so any side effects are performed: printf("%d ", array[exit(1),0]); will not print anything.

Can anybody explain the error in the program i made, can anybody why i didn't workout?

how is your day :),
Take a look at the below program, the program written below is to calculate the sum of first n natural numbers, the problem is that i get the sum of n-1 natural numbers, can anybody explain why ?
and can anybody also explain why a-- instead of --a.
#include<stdio.h>
main()
{
int a,sum;
printf("Enter a number.");
scanf("%d",&a);
sum=sumnat(a);
printf("Sum of the first %d natural numbers is %d.",a,sum);
}
sumnat(a)
{
int b;
if(a==0)
{
return 0;
}
else
{
b=a+sumnat(--a);
return(b);
}
}
There were several errors, the greatest of which was undefined behaviour in the expression which uses a and also a modified value of a. You should also define your function properly, not rely on default values provided by the compiler.
#include <stdio.h>
int sumnat(int a); // function prototype
int main(void) // correct signature
{
int a, sum;
printf("Enter a number. ");
scanf("%d", &a);
sum = sumnat(a);
printf("Sum of the first %d natural numbers is %d.", a, sum);
return 0;
}
int sumnat(int a) // function has a return type and argument type
{
if(a == 0)
{
return 0;
}
return a + sumnat(a - 1); // there was no need to decrement `a`
}
Program session
Enter a number. 5
Sum of the first 5 natural numbers is 15.
Your program works for me, using gcc on Mac OSX. However, it will not work everywhere, because of this line:
b=a+sumnat(--a);
--a decrements a, but if it does so before the addition, then your result will be wrong. I'm not sure C is required to evaluate expressions strictly left-to-right (I don't think it is). At any rate, since you don't use a after that line, you could fix things this way:
b=a+sumnat(a-1);
As #self says, you should fix the program to handle negative values, and it would be a good idea to consider what is the largest natural number whose sum you can compute this way (and why that is).
There is a difference between them. One first subracts from a and than goes in the function while the other frist goes in... so it never gets subracted and you go to inifinit stack.
"and can anybody also explain why a-- instead of --a"
When you use the prefix operator --a the decrease is done before anything else, while the postfix operator a-- happens after the rest of the expression is resolved, so, lets say, while debugging your code, in a particular moment, a = 5
since the line
b=a+sumnat(--a);
is using the prefix version of the operator, the decrement would happen immediately, making a=4 and then the function sumnat would be called with argument 4
b=a+sumnat(a--);
in this case the postfix operator is being used, so first the function sumnat would be called with the argument 5, since that is the value of a in that moment, then, only when the function returns a value (which would never happen in your example, since it would be called multiple times with the same value, never reaching 0) the decrement would happen

printf and ++ operator [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 4 years ago.
#include<stdio.h>
main()
{
int a=10;
printf("\n %d %d", a, a++); //11 10
a=10;
printf("\n %d %d", a++, a); //10 11
a=10;
printf("\n %d %d %d ", a, a++,++a); //12 11 12
}
after running this I got the output given in comments. as far as I know first output is expected because execution of printf goes from right to left but could not understand second and third
Nothing goes "from right to left" in function argument evaluation. When function arguments are evaluated, the order of evaluation is unspecified and there are no sequence points between evaluating separate arguments. This means that there's absolutely no temporal ordering in this process. The arguments can be evaluated in any order, and the process of their evaluation can be intertwined in any way.
However, your code suffers from even worse problems. All three statements that call printf produce undefined behavior (UB) because they either make an attempt to modify the same object (a) twice without a sequence point between the modifications (the third call), or they attempt to modify an object and read it for an independent purpose (the first and the second call). So, it is too early to even mention the order of evaluation. Your code's behavior is undefined.
None of the outputs can really qualify as unexpected. All the arguments to a function are evaluated before entry to the function itself -- but the order of their evaluation relative to each other is unspecified, so all of these results are allowed. Officially, your last one (that has two separate instances of incrementing a) has undefined behavior, so it doesn't have to do anything sensible at all.
++a means increment a first, and then return evaluate the expression. (a changes, and the expression evaluates as a + 1)
a++ means evaluate a (so, erm, a), and then increment it. So a is passed, but the value of a is then (ie afterwards) changed to a+1.
You are invoking undefined behaviour by referencing both 'a' and 'a++' in the argument list.
It is not defined which order the arguments are evaluated in. Different compilers may choose different orders. A single compiler can choose different orders at different times.
Do not do it!
Function parameters are not evaluated in a defined order in C. Therefore one cannot tell beforehand if a or a++ will be evaluated first when calling printf.
See Parameter evaluation order before a function calling in C

Resources