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);
}
Related
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.
In C
int n=100;
printf("%d", (int)(sqrt((double)n)));
When I use this code it prints the correct answer (10).
But following code always prints 0
int n;
int max = (int)(sqrt((double)n));
printf("%d", max);
Why are the answers are different ?
int n=100;
printf("%d", (int)(sqrt((double)n)));
In this case, the value of n is known i.e, 100. So sqrt((double)n) returns the correct value.
int n;
int max = (int)(sqrt((double)n));
printf("%d", max);
Here, the variable n is uninitialized. The variable could be holding an indeterminate value depending upon whether it is declared locally (inside a block, in which case the value of n would be a junk value) or globally (outside a block, in which case the value of n would be zero). Always initialize your variables to avoid such errors.
I have a doubt in the very basics of C .
I have written the following code. Here in the add() function, I'm not returning anything and so I expected that the output will be some junk value or something, but it didn't happen like that. Can anyone explain to me why it was happening like that? Please excuse me if I have written something wrong in the code.
To my understanding, I thought the memory for variable add1 will be from stack and hence once the add() is done , all the memory allocated will be freed, thus some junk value will be displayed.
My clear doubt is without returning anything, how can it print the correct value?
Code sample:
main() {
int x = 4, sum;
int n;
printf(" enter a number \n");
scanf("%d", &n);
sum = add(x, n);
printf(" total sum = %d\n", sum);
}
add(int x, int n) {
int add1 = 0;
add1 = x + n;
//return(add1);
}
This is undefined behavior.
When you don't specify what a function returns, it will default to int. Then when you don't have a return statement, it will be undefined what happens. So in principle anything may happen.
For gcc, it will on many system just return some "random" value. In your case it just happens to be the sum. Simply by "luck".
Always turn warnings on during compilation, e.g. gcc -Wall and always treat warnings as if they were errors.
Your code should look something like:
#include <stdio.h>
int add(int x,int n); // Corrected
int main(void) // Corrected
{
int x=4,sum;
int n;
printf(" enter a number \n");
scanf("%d",&n);
sum = add(x,n);
printf(" total sum = %d\n",sum);
return 0; // Corrected
}
int add(int x,int n) // Corrected
{
int add1=0;
add1 = x+n;
return add1; // Removed the // to uncomment and removed unnecessary ()
}
As stated before, this is undefined behavior, and you shouldn't rely upon it.
However, there is some logic behind what is going on. The return value for a function is, by convention, stored in the eax register on x86, or the rax register on x86_64. It just happens that your compiler is also using the eax or rax register for storing the calculated value. Also, since the return type of add() is not specified, it is implicitly defined as int.
I am trying to write a simple program. I am a begineer and i am not getting a value to total. When i am trying to print . I am getting a address as output . Can anyone explain me what is the mistake and correct my program .
#include<stdio.h>
void main()
{
int first,second,total;
printf("enter the value for the first");
scanf("%d",&first);
printf("enter the value for the second");
scanf("%d",&second);
total=power(first,second);
printf("The value for power is %d",power);
}
int power(int doom1,int doom2)
{
int temp=doom1;
int i;
for(i=1;i<=doom2;i++)
{
temp=temp*doom1;
}
return temp;
}
You are printing the wrong variable:
total=power(first,second); //here you are getting return value in variable total
printf("The value for power is %d",power); // power is the function name not variable
Replace this line with:
printf("The value for power is %d",total); // you need to print `total`
Also you have to declare your function prototype before main():
int power(int ,int);
and you should use int main():
int main()
{
// your code
return 0;
}
In addition to passing total to printf instead of power, as you are just starting, make a point to always give your variables an initial value (initialize them). This prevents an attempt to read from uninitialized space which is the bane of new C programmers. (it will save you a lot of headaches). Attempting to read from an uninitialized variable is Undefined Behavior. That can result in anything from slipping by unnoticed, to causing your program to crash. It is to be avoided.
Also, as I explained in the comment, in C, the function main() is type int and it returns a value to its caller (usually the shell, or another program). When using main without arguments, the proper form is:
int main (void)
When accepting arguments, the proper form is:
int main (int argc, char **argv)
In either case, it should return a positive value upon completion. A return 0; at the end is all that is required. exit (0); is another function you can use to return a value. You will also see the form of main with arguments written as:
int main (int argc, char *argv[])
The first and second forms are the practical equivalents of each other, the first recognizing that an array passed to a function in C will decay to a pointer. But for now, just understand that they are equivalent.
You also have an error in your my_power calculation. int temp = doom1; should be int temp = 1; Your calculation was returning a value twice the actual product.
Your style of syntax is up to you, but I would suggest that expanding your syntax a little by using discretionary spaces and lines will make your code much more readable and make finding errors a bit easier. Here is an example regarding all of these points:
#include <stdio.h>
int my_power (int doom1, int doom2);
int main (void)
{
int first = 0; /* Always initialize your variable to prevent */
int second = 0; /* an inadvertant read from an unitialized */
int total = 0; /* value which is Undefined Behavior (bad). */
printf ("\n enter the value for the first : ");
scanf ("%d",&first);
printf (" enter the value for the second: ");
scanf ("%d",&second);
total = my_power (first,second);
printf ("\n The value for my_power is: %d\n\n", total);
return 0;
}
int my_power (int doom1, int doom2)
{
int temp = 1;
int i = 0;
for (i = 1; i <= doom2; i++)
temp = doom1 * temp;
return temp;
}
Output
$ ./bin/simple_function
enter the value for the first : 2
enter the value for the second: 7
The value for my_power is: 128
you are trying to print "power" without parameter
printf("The value for power is %d",power);
you should do
printf("The value for power is %d",total);
or
printf("The value for power is %d",power(first,second));
This piece of code is giving unexpected output. When I comment printf of sumdig function the return value of a is 6 and b is 12 but when printf is retained a is 5 and b is 6. Please explain.
main()
{
int a,b;
a = sumdig(123);
b = sumdig(123);
printf("\na=%d b=%d",a,b);
return 0;
}
int sumdig(int n)
{
static int s=0;
int d;
if(n!=0)
{
d=n%10;
n=(n-d)/10;
s=s+d;
sumdig(n);
}
else
return s;
printf("\n s=%d",s);
}
If you don't have an explicit return statement an int c function is apt to return whatever value was returned by the last function called (although I believe the actual behavior is undefined). Therefore
you are returning the result of printf when you mean to return the value of the recursive call to sumdig.
Instead of sumdig(n);, try return sumdig(n);
Right, firstly you should compile this with as many warnings as your compiler will give you.
This'd show you that although sumdig returns a value, there's at least one code path that doesn't return anything so the caller will get rubbish.
Secondly you have a static variable that is never re-initialised so every client call will accumulate extra stuff in s.