#include<stdio.h>
void print();
int main(){
print();
print();
return 0;
}
void print(){
static int x;
x=10;
x+=5;
printf("%d\t",x);
}
Output 15 15
You have code that says:
x = 10;
x = 15;
and that then prints x.
Then you call that function two times.
Why again do you think that the second print should result in a different outcome; compared to the first one?!
You see, you start by assigning: 10. Plus 5. Why should that ever result in 20?
Hint - try changing your code to:
static int x = 10;
x += 5;
Long story short: re-assigning is not the same thing as re-initializing!
I think you are getting confused with Reassigning and Re-intializing of static variable. You must have learnt somewhere that static variable dosn't re-initialize itself whenever the function gets called. Hence you are expecting answer 15 & 20.
But the thing is that you are re-assigning the value of x with 10 each and every time. If you modify your code like following then you can achieve what you've expected.
static int x=10;
x+=5;
Here, x gets initialized with 10 first time only. After that, for each and every function call, it will get incremented by 5 only.
Hope this will help and make your doubt clear.
Here static variable declared(initialized) as x, then value assigned every time 10 not initialize.
So, output of your program 15 and 15 displayed.
initialization and assignment both are different. please read this stack overflow question.
I hope this will help you and make your doubt clear.
Related
The values which are output from inside the called function and from inside the calling function are not identical.
Why are values of y and value of m not the same?
screenshot of code and output, showing "Value of m 6" and "value of y 13"
#include<stdio.h>
int pass(a);
int main()
{
int x,y;
printf("Hello world\n");
printf("Enter the x ");
scanf("%d",&x);
y = pass(x);
printf("value of y %d",y);
return 9;
}
pass(m)
{
m = m + 5;
printf("Value of m %d\n",m);
// return 5;
}
Output:
Hello World
Enter the x 1
Value of m 6
value of y 13
Strictly, this should not even attempted to be explained, because of undefined behaviour, compare Reaching end of function without return statement
but ...
Assuming that my guess on the pattern of returned values (a constant plus the number of digits in "input + 5") is correct:
By chance, the default assumptions of the compiler when seeing the incomplete prototype int pass(a); (should be int pass(int a);), allow it to associate the later provided implementation of pass(m) (should be int pass(int m);, or more consistently int pass(int a)).
So when you call y = pass(x);, y gets the value returned by that implementation.
The implementation then lacks a clean return statement (it has one, but inactive by being a comment).
So at the end of executing that function, the most recently determined result is returned, another default of compilers which you should better not rely on for clarity and readability of code.
The most recent result is the return value of the call to printf().
That return value is the number of successfully printed characters.
You might want to read up on printf() and its return value in its specification, and about the concept of return values, prototypes and data types of parameters and return values in general.
For the output you show in your picture of text,
Value of m 6\n (thanks for making me type that...) that is, let me count
^ ^ ^ ^
1 5 10 13,
13, including the newline at the end of the output from inside the function.
Obviously, this is completely unrelated to the value of the local variable m, which is seen in the picture of text.
For more details on how to achieve what you might try to do see the comment David C. Rankin.
#include <stdio.h>
int print1(void)
{
static int x= 10;
x+=5;
return x;
}
int print2(void)
{
static int x;
x = 10;
x+= 5;
return x;
}
int main()
{
int x;
x = print1();
x+= print1();
x+= print2();
x+= print2();
printf("%d", x);
return 0;
}
My solution:
First in print1 statement the value of the will increment by 5 , x will be 15 .
Then upon calling print1 function for the 2nd time it will be 15+5=20, since it will hold the previous value.
Now for the function print2, it will again initialise the x value with 10, then increment it by 5. Value of x will be 15.
for the last statement value of x will be 15+5=20.
x=15+20+15+20=70
But the answer is 65. Please correct me where did I go wrong? I even wrote it in my compiler, it is giving output 65, but if change the position of x inside Print2 statement like static int x=10, it is giving different output?
Why this is happening?
The init of a static variable like static int x=10; only happens once per program execution. And that is not like a statement being executed, it is during setup of variables for the program.
The assignment statement x = 10; is executed each time the function is executed.
This means the two code versions you discuss are different and especially have different effects on variable values; which in turn explains the different output.
I'm making a code for converting Decimal numbers to Binary(university assignment). If I only do DecToBinary(5) it gives me 101, and if I only do DecToBinary(6) it gives me 110, but when i do both of these statements in main() it gives me 101110101 when it should just give me 101110(joining the two answers above). I don't understand what is going on since it should just call DecToBinary(5) and print 101 then (without adding a newline character) call DecToBinary(6) and print 110.
void DecToBinary(int dec){
int temp[64]; //64 is just a max value
int i,j;
while(dec>0){
temp[i]=dec%2;
dec=dec/2;
i++;
}
for(j=0;j<i;j++){
printf("%d",temp[i-1-j]);
}
}
You haven't initialized the variable i. This means that the behaviour of your program is undefined, as the value of i may be different of 0 which is what you want.
To correct it, you just have to initialize i when declaring it, meaning int i = 0
The variable i is not initialized
int i,j;
so the function has undefined behavior.
You need to initialize it before the while loop.
Also the while loop should be substituted for a do-while loop. Otherwise the value 0 will not be processed correctly. For example
i = 0;
do
{
temp[i++] = dec % 2;
} while( dec /= 2 );
Also as the function does not process negative numbers then its parameter should have the type unsigned int
void DecToBinary( unsigned int dec )
Always initliaze variable. Check i and j in your case.
I'm running a simple code to test my understanding, as of below.
The output that I got from this is actually 10.
I thought that the output should gave me a compile error, as "b" couldn't be add to x, as x is a const variable.
Can someone help to clear my understanding on this?
int aFunction(const int x){
return (x+10);
}
int main(){
int b =0;
b = aFunction(b);
printf("%d\n",b);
return 0;
}
This line
return (x+10);
Doesn't add 10 to x and return it. It forms the value that is x+10 and returns that but leaves x itself unchanged.
If you wrote
int c;
c=x+10;
Would you expect x to be increased by 10 after that second line executes?
Try
int aFunction(const int x){
int c=(x+10);
printf("aFunction: x=%d c=%d\n",x,c);
return c;
}
Basically, applying the const qualifier to a variable prevents the value of the variable from being modified.
In your function, aFunction(), the variable x is given a const qualifier which prevents the value of x from being modified in your function. There is no reason why your code shouldn't be able to compile since all the function is doing is returning a value which is 10 more than x. It is not in any way modifying the value of x.
If you did something like x += 10 which is short for x = x + 10, then you will get some compiler errors.
const int x only means that x itself cannot be changed inside the function. It has nothing to do with the return value.
Simple:
x is not changed until or unless you re-initialize it, look into these lines :
const int x : means X will never be changed.
x+10 : means just add 10 in X but never save the status.
x = x +10 " means overwrite the value of x which will Crash: and you will get desired Error
Does anyone know why my program prints -69 in below case? I expect it to print default/ garbage value of uninitialized primitive data types in C language. Thanks.
#include<stdio.h>
int a = 0; //global I get it
void doesSomething(){
int a ; //I override global declaration to test.
printf("I am int a : %d\n", a); //but I am aware this is not.
a = -69; //why the function call on 2nd time prints -69?
}
int main(){
a = 99; //I re-assign a from 0 -> 99
doesSomething(); // I expect it to print random value of int a
doesSomething(); // expect it to print random value, but prints -69 , why??
int uninitialized_variable;
printf("The uninitialized integer value is %d\n", uninitialized_variable);
}
What you have is undefined behavior, you can't predict the behavior of undefined behavior beforehand.
However it this case it's easy to understand. The local variable a in the doesSomething function is placed at a specific position on the stack, and that position does not change between calls. So what you're seeing is the previous value.
If you had called something else in between, you would have gotten different results.
Yeah.. Your function reuse two times the same segment of memory.. So, the second time you call "doesSomething()", variable "a" will be still "random".. For example the following code fill call another function between the two calls and you OS will give you differen segments:
#include<stdio.h>
int a = 0; //global I get it
void doesSomething(){
int a; //I override global declaration to test.
printf("I am int a : %d\n", a); //but I am aware this is not.
a = -69; //why the function call on 2nd time prints -69?
}
int main(){
a = 99; //I re-assign a from 0 -> 99
doesSomething(); // I expect it to print random value of int a
printf( "edadadadaf\n" );
doesSomething(); // expect it to print random value, but prints -69 , why??
int uninitialized_variable;
printf("The uninitialized integer value is %d\n", uninitialized_variable);
}