External/global variable in C - c

I am learning about global variables in C using book C programming a modern approach.
Below is given an example from the book why using same global variable for multiple functions is bad idea.
I don't understand why function print_all_rows executes function print_one_row only once.
Let's say I call first function print_one_row and then function print_all_rows.
At the beginning of program i is set to 0 by default by compiler. Once program finishes execution of print_one_row function the value of i is 11.
Program enters into function print_all_rows, sets i to 1, calls function print_one_row and then increments i to 12 instead of 2.
Why is it incrementing i to 12 and not to 2 if I changed the value of i to 1?
int i;
void print_one_row(void)
{
for (i = 1; i <= 10; i++)
printf ("*" ) ;
}
void print_all_rows(void) {
for (i = 1; i <= 10; i++) {
print_one_row();
printf ("\n") ;
}
}

In print_all_rows, just before the first call to print_one_row, i has the value of 1.
Then print_one_row is called. When that function returns, i has the value of 11. Then the loop increment in print_all_rows is evaluated which increments i from 11 to 12, then the condition is evaluated which is false, then print_all_rows returns.

Because i is glocal variable (common for both functions) and its value is 11 after first call of print_one_row. With this value (11) the second iteration of for loop in print_all_rows exits and there are no more calls of print_one_row.

Related

Do while loop not working inside a function in C [duplicate]

In the following code, would anything be returned?
#include <stdio.h>
int try_this (int in);
int main (void)
{
try_this (5);
}
int try_this (int in)
{
int i = 1;
for (i = 0; i < in; i = i + 2) {
return i;
}
return i;
}
Since there's a return in the for loop, would the code just return nothing since there's nothing after the function is called? Or would i be returned as a number, like 1(because of the declaration in try_this) or 6(because of the loop)?
Thank you!!:)
When the first return statement is encountered, the function will return. It's easy to see that the function will start the loop and while i=0 it will return i. So each time you call try_this you'll get 0
Also, return 0; from main...
When you enter the for loop for the first time, i is 0 and less than the 5. Then it execute the statement return i; in for loop, which will finish executing the try_this() funciton.
What you are basically asking is that if the function will return something even though there is no code after the function call.
The answer is yes, it will return. It doesn't matter if there is code later or not. The function will return (in this case 0) It's just that there's nobody to catch it.
The function try_this() always returns 0:
i is initially set to 1
then i is set to 0 in the initial clause of the for statement
if i < in, the loop body is executed and the value of i is returned, namely 0.
otherwise the loop is skipped and the next statement is return i; so 0 is returned too.
Regarding the main function: it ignores the return value of try_this(5) and reaches the end of its body without a return statement. This is bad style and would trigger undefined behavior for any other function, but since C99 the behavior is defined as a special case for the main function and the value 0 is returned to the startup code, which exits back to the system with a termination status of 0, which means successful execution.
if you want to store the value of 'I' i would recommend you to use "while loop"
int i = 0;
while(i < in)
{
i++;
}

Can someone explain output of this C program? [duplicate]

This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 4 years ago.
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
main();
printf("%d\n", i); // will this line executes ?
}
return 0;
}
Output:
0
0
0
0
does code below main(); printf statement instructions is placed to stack every time when main recursive calls happens and executed while terminated from this program?
i is reduced by successive calls to main until zero is reached.
Then printf is called for each level of recursion.
(Note that the behaviour of calling main from itself is well-defined although ill-advised in C, in C++ the behaviour is undefined.)
if (--i)
This will evaluate true the first time (--i == 4). The code recurses into main(). (Recursion: A function calling itself.)
As i is static, it will retain its value of 4 (as opposed to an automatic variable, which would be initialized to 5 again). The if (--i) in this second execution of main() will again be true (evaluating to 3), and will again call main() (for a third execution of the function).
The same for --i == 2 and --i == 1, for four executions of main() (including the first, non-recursive one) total that are evaluating the if condition to true.
The next recursion will evaluate the if condition to --i == 0, and thus false. Skipping the if clause, the function call will just return. i is zero at this point, and -- being static, i.e. only one persistent i for all instances of main() -- will remain at that value.
The main() call one level up the stack -- the one that evaluated --i == 1, then called main() and was waiting for it to return -- will now continue with the statement after the call to main(), and printf() the current value of i... which is 0.
The same happens three more times (for a total of four) until the top-most main() returns. You get four times the current value of i, which is 0.
Note that calling main() from your program is allowed in C, but not in C++. This is specifically for calling main() recursively; for other functions, it is allowed in either language.
(--i) will decrease the value of i to 4 when it is called for the first time and it will continue the decrement of i until (i==0) due to recursion.
Since you have declared the variable i with static keyword and hence a single memory is allocated to it and all the changes are reflected back to it

C program recursive call to main() with and without parameters

Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?
#include <stdio.h>
int main()
{
static int i = 2;
if (i<7)
{
main();
printf("%d ", i);
i++;
//main(10);
}
}
-
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
//main();
printf("%d ", i);
main(10);
}
}
You are calling main() first and then incrementing i
if (i<7)
{
main(); // <-- main called when i still 2
printf("%d ", i);
i++; // <-- statement never reached
//main(10);
}
Hence, while main() calls main() recursively, the statement i++ is never reached.
You should increment i before calling main()
if (i<7)
{
i++;
main();
printf("%d ", i);
//main(10);
}
1st case the i++ after the call of main(), that means the program has no chance to add the i, and into infinity loop, and stackoverflow! haha....
but the 2nd case, it's reduce the i before you call the main.
TL;DR StackOverflow (Pun or no pun, it's true both ways).
First: Some important information
This case has nothing to do with passing an argument to main() or not. Actually, as per the latest C standard, C11, for a hosted environment, the conforming signature of main() is int main(void) and following that, main(10); is wrong, altogether.
Now, coming to the actual problem here,
In the first case, change of i value happens after the call to main(), so in effect, the value of i never get changed because the control never reaches the statement which modifies i. Hence, it's an infinite loop, and because of the recursive call to main(), stack overflow happens.
In later case, i value gets updated before call to main(), so that value actually reflects. Thus, at some point (after 4 occurrences, actually), the if condition meets a FALSE condition and the recursive call ends and the stack unwinds.
First case:
i++ is positionned after the call to main. So i will always be equal to 2, as you never reach this part of the code. You are then calling your main function everytime, leading to an infinite recursion, and thus to the segmentation fault. The fix for this case would be to increase i before calling the main function.
if (i<7)
{
i++; // Increment before calling the main function, so i value is changed
main();
printf("%d ", i);
}
Do note that it will lead to something which looks like your second case, except that you will print several "7".
Seconde case:
In the second case, you are decreasing the value of i everytime you enter your if condition. When you finally can't enter your if condition anymore, it means i is equal to 0 (as if(0) is equivalent to if(false)). Everytime you will return to the previous called main function, i will still be equal to 0, explaining why you are displaying "0" everytime. If you want to print the different values, you can place your printf before the call to the main function for instance.
In the first case:
"i" is never incremented therefore you run in an infinite loop and get an overflow.
In the second case:
You call the recursion before displaying the value of "i", after four calls "i" equals to 0 and your recursion stack unwinds.
Modify your condition and perform outputs before the recursion call.
In the first case, i is never incremented, hence, the main keeps getting called and soon enough there is no more stack memory available to the program.
In the second case, the last updated value of i is intact throughout the lifetime of i. As i is static, program is referring to the same memory address on all the iterations. While printing i you see the last updated value, that is 0, as output.

Explain the reason for such output of this C program

Please help me to understand the output of the following C program.
#include "stdio.h"
int fun(int x)
{
static int a=0;
return x+a++;
}
int main()
{
int i;
for(i=0;i<5;++i)
printf("%d ",fun(printf("%d",0)));
return 0;
}
output is : 01 02 03 04 05
why not : 1 2 3 4 5
The first 0 is the result of the execution of the printf() statement inside the fun() function call
fun(printf("%d",0))
and the second 1 is the result of the outer printf() which prints the return value of the fun() function call. The fun() function call sends the return value of the inner printf() which is always 1, and since you have initialized the variable a as static the value of a remains same and is added everytime with the function call.
since you are always printing 0 in the printf() inside the fun() function call, hence the 0 before the numbers.
The arguments are evaluated in order when you call printf here:
printf("%d ",fun(printf("%d",0)));
The outer printf call needs to evaluate all its arguments, which is the following:
fun(printf("%d",0))
Which then calls the inner printf to evaluate all of its arguments.
First, printf("%d",0) will be evaluated, and evaluate to the number of characters printed (since this is what printf() returns). This is passed to fun next, which will return the number of characters the printf printed (1) plus the number of times it has been called (due to the static int a). That will then be passed to the outer printf, printing the second number, then a space.
The reason is that in this statement
printf("%d ",fun(printf("%d",0)));
function printf is called twice. At first it is called as the argument expression of function fun
fun(printf("%d",0))
and outputs aways 0.
The second time the function is called with the resut of the call of function fun Take into account that the value of call
printf("%d",0)
is always equal to 1.
imagine your commands in the way that it is evaluated:
printf("%d ",fun(printf("%d",0)));
is equivalent to:
int printf_result = printf("%d",0);
int fun_result = fun(printf_result);
printf(("%d ",fun_result);
this is c. this is not python or matlab. if you assign the result value it doesn't influence the effects of the function call.

count_calls() function and the return value

im going through an old exam past paper and had this question
int c = 0;
int count_calls()
{
c = c + 1;
return c;
}
Now it asks why would this go wrong i.e. the number of calls counted is incorrect? is it right to say that no matter what c is set to in the count_calls() function it will always be zero due to the fact c is always defined as 0 outside the class? and would changing it to ++c or +CC fix this issue?
function increments global variable (and it will be correctly incremented by 1 every time the function was called), but when it returns, it creates local copy.
in the range of int type, it can count calls
generally speaking, it's bad code (it can't be used in parallel)
it wouldn't changed with moving to ++c

Resources