How does the for loop run in such a case? - c

#include <stdio.h>
int f1(){
static int val=11;
return --val;
}
int main()
{
for( f1(); f1(); f1()){
printf("%d",f1());
}
}
The output of the program is :
8 5 2
Could someone explain me what does for(f1();f1();f1()) do?

#include <stdio.h>
int foo(void) {
static int val = 11;
return --val;
}
int main(void) {
int (*f1)(void) = foo; //4 function pointers to the same function
int (*f2)(void) = foo;
int (*f3)(void) = foo;
int (*f4)(void) = foo;
for (f1(); f2(); f3()) {
printf("%d", f4());
}
}
The execution goes like this
val = 11
f1() 10
f2() 9 "true"
f4() print 8
f3() 7
f2() 6 "true"
f4() print 5
f3() 4
f2() 3 "true"
f4() print 2
f3() 1
f2() 0 "false"

For easier understanding I'll talk about functions as such:
for (A(); B(); C()) {
printf("%d", D());
}
So understand that all A B C and D are calls to f1() but I want to be able to differentiate them.
1st thing to understand is how are the "parameters" of for working.
1st one is the init part, it will be executed once only, before the evaluation of the first condition.
2nd one is the condition part, it will be executed before every loop, to check if it needs to keep looping or stop.
3rd one is the conclusion part, it will be executed after every loop, before the next evaluation of the condition.
We can then understand that your program will execute in this order:
call A() to initialize the for loop => val = 10;
call B() to check condition => val = 9
call D() in your printf => val = 8 gets printed
call C() to end an iteration => val = 7
call B() to check condition => val = 6
call D() in your printf => val = 5 gets printed
call C() to end an iteration => val = 4
call B() to check condition => val = 3
call D() in your printf => val = 2 gets printed
call C() to end an iteration => val = 1
call B() to check condition => val = 0 condition ends

The C for loop contains 3 items:
the initialisation
the condition
the incrementation
A for loop run until the condition is equal to either 0 or null.
You enter the loop, it call f1() a first time in the initialisation so val equal 10
At each iteration, it will call f1() three time, to check the condition, to do the increment part and in the printf call. Thus at each iteration we have val = val - 3
Once val == 0 you exit the loop.
Note that it only work because val is static thus not being reinitialised at each call of f1()

Related

Is it necessary to put return in a void recursion?

Feel free to make this post as a duplicate if the question asked already, I haven't found a post same as this
As far as I know that there's no need to return in a void function, e.g:
void ex () {printf ("Hi\n");}
But, is it fine if there's no return in a void recursion? What I'm thinking is, the program will keep calling func (num-1) until it reaches 0 and it returns so it doesn't print 0 to the output, and I need return at the end of the function so after the recursion call is done, you go back to the previous func () immediate caller.
Here's the code,
#include <stdio.h>
void func (int num)
{
if (!num) return;
func (num-1);
printf ("%d\n", num);
return; //Is it necessary to put return here?
}
int main ()
{
func (10);
return 0;
}
Output,
1
2
3
4
5
6
7
8
9
10
Without the last return, it works just fine too, or am I missing something?
A function with return type void doesn't need an explicit return. Simply reaching the end of the function will properly return.
It is no different for void functions that are also recursive. The first return in your function is required because you want it to return before reaching the end of the function, but the second isn't required.
A function returning void doesn't have to explicitly return. A program has 1 entry point, but might have multiple exit points. Consider the following example:
void print(int var)
{
if (var)
return; // first exit point
/*
* do stuff
*/
// second exit point
}
It has 2 exit points. Second one is without a return;.
try this :
#include <stdio.h>
void func (int num)
{
if (!num){
printf("0\n");//print 0 before you stop
return;
}
func (num-1);
printf ("%d\n", num);
}
int main ()
{
func (10);
return 0;
}

Variable inside if block is shown in call stack even though the if statement didn't get evaluated to true

I have a piece of code in C as shown below-
In a .c file-
1 custom_data_type2 myFunction1(custom_data_type1 a, custom_data_type2 b)
2 {
3 int c=foo();
4 custom_data_type3 t;
5 check_for_ir_path();
6 ...
7 ...
8 }
9
10 custom_data_type4 myFunction2(custom_data_type3 c, const void* d)
11 {
12 custom_data_type4 e;
13 struct custom_data_type5 f;
14 check_for_ir_path();
15 ...
16 temp = myFunction1(...);
17 return temp;
18 }
In a header file-
1 void CRASH_DUMP(int *i)
2 __attribute__((noinline));
3
4 #define INTRPT_FORCE_DUMMY_STACK 3
5
6 #define check_for_ir_path() { \
7 if (checkfunc1() && !checkfunc2()) { \
8 int temp = INTRPT_FORCE_DUMMY_STACK; \
9 ...
10 CRASH_DUMP(&sv);\
11 }\
12 }\
In an unknown scenario, there is a crash.
After processing the core dump using GDB, we get the call stack like -
#0 0x00007ffa589d9619 in myFunction1 [...]
(custom_data_type1=0x8080808080808080, custom_data_type2=0x7ff9d77f76b8) at ../xxx/yyy/zzz.c:5
temp = 32761
t = <optimized out>
#1 0x00007ffa589d8f91 in myFunction2 [...]
(custom_data_type3=<optimized out>, d=0x7ff9d77f7748) at ../xxx/yyy/zzz.c:16
temp = 167937677
f = {
...
}
If you see the code, check_for_ir_path is invoked from both myFunction1() and myFunction2().
And inside check_for_ir_path, there is a check inside if block like - checkfunc1() && !checkfunc2(). If that check evaluates to TRUE then a SIGSEGV is fired and the process is crashed intentionally. And the variable temp is declared only if that condition passes.
Now if you look at the call stack, you can see the local variable temp shown even in the StackFrame_1. However it didn't crash inside the function myFunction2. How could this be possible?
If i declare another variable, say 'int temp' just after the statement int temp = INTRPT_FORCE_DUMMY_STACK;, that is not shown as part of bt full
How could this be even possible?
Compilers are allowed to reorganise your code in any way that doesn't change the outcome of the program. So if you write:
void foo()
{
if (something)
{
int sv;
...
}
}
the compiler is allowed to change it into something equivalent to:
void foo()
{
int sv;
if (something)
{
...
}
}
regardless of something being true or false.
But the compiler must make sure that this will fail to compile:
void foo()
{
if (something)
{
int sv;
...
}
sv = whatever; // Compiler error....
}

what is the working rule of this program, Explanation?

i am little confuse in this program i want if anyone could explain to me the functionality of this code and the output, i am getting the output of this program as such
1
1
2
2
3
3
All i want to know the working rule of that two functions how they calculating the values?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int M(const int n);
int F(const int n)
{
return(n==0)?1:n-M(F(n-1));
}
int M(const int n)
{
return (n==0)?0:n-F(M(n-1));
}
int main()
{
int i;
for(i=0;i<6;i++)
{
printf("%2d\n",F(i));
}
printf("\n");
return 0;
}
Consider on for
for(i=0;i<6;i++)
{
printf("%2d\n",F(i));
}
Short answer:
F(0) => 1;
F(1)=> 1 - M(F(0))
when F(0):1 then F(1) = 1 - M(1)
go to calculate M(1), but we start from 0, M(0)= 0;
M(1) = 1- F(M(0)) = 1- F(0) = 1-1=0;
last we have M(1) = 0; and as F(1) = 1-M(1) = 1-0=1
last we have: F(1)=1
More complete:
Let see F() way of working.
the last command in F(),
return(n==0)?1:n-M(F(n-1));
expanded to
if (n==0){
return 1;
}else{
return n-M(F(n-1));
}
In first for iteration i:0, we want F(0) as n is zero, (n:0), the if (n==0) is true , return 1; is executed and value ofF(0) have to be 1.
for second iteration we want F(1), for that if (n==0) is false and else block is execute.
as now the n:1, F(1) = 1 - M (F(0)).
In previous iteration we have F(0)=1, OK now we can rewire or equation: F(1) = 1 - M(1), it obvious that if we have value of M(1) simply , put it on to the last formula , F(1) have been solved.
for this we must expand M() function.
Similarly we can write for M().
if (n==0){
return 0;
}else{
return n-F(M(n-1));
}
M(0) = 0;
M(1)= 1- F(M(0))= 1- F(0) = 1 - 1=0;
now we have M(1) = 0; by putting it on the F(1) = 1 - M(1)
we achieve to F(1) = 1.
Now the first two pair of 1 in output of your code is calculated by hand.
for others, do this way over and over.
As suggested in the comments try to trace the code by hand, I will go through the first two iterations with you so you get the idea
When your program starts it calls your main function, and starts executing the for loop as follows:
i=0 => calls F(n=0) => is n==0 true? Yes => return 1 => print 1
i=1 => calls F(n=1) => is n==0 true? No => then 1-M(F(0)) => F(0) calculated from the previous iteration to return a value of 1 => call M(n=1) => is n==0 true? No => then 1-F(M(0)) => M(0) returns 0 since n==0 is true => then 1-F(M(0)) is equal to 1-F(0) => we calculated F(0) to return 1 => so 1-F(0) return 0 from M => take the return back to 1-M(F(0)) => 1-0 = 1 => print 1
Do not be frustrated because what you are asking would be actually much easier to understand with some patient. I extremely recommend that you hold down a pen and paper and start tracing yourself.
Go iteration by iteration as I did.
Call each function according to the correct flow of the if conditions.
When you call a function, mark where you have left in the code to jump to said function, such that once it returns a value, you know exactly where to place the returned value.
Peace of paper, patience, and trace.

Simple Recursion output calling recursion twice

This is how I tried it. The main part uses fun(9). So 9 does not equal or less than one. And it calls fun(9/3) two times and prints n which is 9. Where am I wrong here?
#include <stdio.h>
void fun(int n){
if(n<=1) printf("*");
else{
fun(n/3);
fun(n/3);
printf("%d",n);
}
}
int main(void){
fun(9);
return 0;
}
When called as fun(9), the code shown does print **3**39.
The first call has n == 9.
Consequently, if calls fun(3), then fun(3) again, and then prints 9.
The first of the two calls fun(3) calls fun(1), which prints a *, then calls fun(1) again and prints another *, and then prints 3.
The second of the two calls does the same.
Your output should be
* * 3 * * 3 9
If you can't see how it works, then do it by hand and fill in the values instead of the variable name:
Pass 1:
void fun(9){ // first pass n=9
if(9<=1) printf("*"); // nope, that's not true
else{
fun(9/3); // call the function again with n = 9/3 = 3
Pass 2:
void fun(3){ // second pass n=3
if(3<=1) printf("*"); // nope, that's not true
else{
fun(3/3); // call the function again with n = 3/3 = 1
Pass 3:
void fun(1){ // third pass n=1
if(1<=1) printf("*"); // yes! so print first *
else{ // this function is only an if and an else, we hit the if
// so it just drops out now
So pass #3 and we hit the lowest level of the recursive call, now Pass 2 will continue execution where it left off:
Pass 2b:
void fun(3){ // second pass n=3 (did this already)
if(3<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(3/3); // call the function with n = 1 (did this already)
fun(3/3); // next recursive call, again with n = 1
Now this will repeat the "pass #3" code, again printing a second *, then it will return and continue execution where it left off:
Pass 2c:
void fun(3){ // second pass n=3 (did this already)
if(3<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(3/3); // call the function with n = 1 (did this already)
fun(3/3); // call again with n = 1 (did this already)
printf("%d", 3); // print 3
At this point the output is: **3 Pass #2 is now complete so we go all the way back up and resume Pass #1 where it left off:
Pass 1b:
void fun(9){ // first pass n=9 (did this already)
if(9<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(9/3); // call the function again with n = 3 (did this already)
fun(9/3); // now call the function again with n = 9/3 = 3
From here you can see that we're going to repeat the Pass 2 logic producing another **3 then we'll return to Pass1 a final time to print the 9
A final output of: **3**39

Is it possible to execute a "C" statement without a semicolon

Post an example to execute a "C" statement without semicolon( ; )
This line is a statement:
while (0) { }
You can an expression in an if() as long as it evaluates to a scalar (integer, floating point number or pointer).
if (expr, 0) {}
According to the C grammar, expr is an expression. if(expr){} is a selection_statement, so this would match the bill.
Note that the ,0 isn't always necessary since the body of the if() is empty. So these would be equivalent statements, if expr returns a scalar:
if (expr) {}
while (expr, 0) {}
while (expr && 0) {}
while (expr || 0) {}
All would evaluate the expression once.
Wrong answer
... with a new right answer below.
int main(void)
{
}
The pair of braces in the definition of main is a compound-statement which is one of the valid forms for a statement.
Edit: although a statement can be a compound-statement, and a function-body consists of a compound-statement, when the compound-statement is a function-body, it's not a statement.
Edit, Edit:
This program does contain a statement which is executed, though:
int main(void)
{
if (1) {}
}
Use this function:
__asm {
mov al, 2
mov dx, 0xD007
out dx, al
}
{ }
At least 15 characters are required to post an answer...
if (i=2) {} // give `i` a value
Even whole program (my GNU C built it despite result code returned is undefined).
The question is WHY?
/* NEVER DO THIS!!! */
int main()
{
{}
}
And in C++ we even can stabilize return code by this simple stack trick with variable
(yes, it is dirty, I understand but I think it should work for most cases):
/* NEVER RELY ON SUCH TRICKS */
int main()
{
if (int i=0) {}
}
int main()
{
// This executes a statement without a semicolon
if( int i = 10 )
{
// Call a function
if( Fibonacci(i) ) {}
}
// I have made my point
return 0;
}
int Fibonacci(int n)
{
return (n == 2) ? 1 : Fibonacci(n - 2) + Fibonacci(n - 1);
}
#define _ ;
int main()
{
return 0 _
}

Resources