Can someone please clarify this code? - c

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.

Related

recursion c, program does not display

im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input.
(Code is about sum of digits enter #example 12345 = 15)
#include<stdio.h>
int sum(int num);
int sum(int num){
int total=0;
if(sum==0){
return total;
}
else{
total+=num%10;
num/=10;
return sum(num);
}
}
int main()
{
int num,k;
printf("Enter 5 positive number: ");
scanf("%d",&num);
printf("Sum is: %d",sum(num));
}
Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases.
Here you are verifying sum the function instead of num the parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.
You just need to change the condition from sum==0 to num==0. It will now print something. However, the logic of your program is still wrong. You can change your sum function to this.
int sum(int num){
if(num==0) {
return 0;
}
return num % 10 + sum(num/10);
}
And you can try learning more about recursion through stack since recursion is basically just stack.
In your code the total gets initialized to zero every time the function is called. and a variable named sum is not initialized. Just change sum==0 to num==0.I have also given the logic to sum the digits of a number.

Printing a recursive function returned value when the function contains printf

#include <stdio.h>
int c=0;
int check (int c)
{
c=c+1;
if (c<6)
return check(c);
printf("%d\n", c);
}
int main()
{
printf("%d\n",check(c));
}
The above code gives me
6
2
as the output. 6 is from the printf function inside the check function but I did'nt get why 2. If I remove the printf function inside the check function I get
5
as the output. Can anyone explain why this happens?
You are invoking undefined behavior. So it behaves oddly.
You must have a proper return statement in the check function as you are supposed to return an int.
Also having printf or not having it - doesn't change anything- it's still UB.(in this case)
I made a few modifications to your posted code so that it becomes obvious what is happening. It looks like the compiler outsmarted you, and prepended return in front of printf("%d\n", c); So the 2 that you are seeing is the number of characters printed when you print 6\n on the last iteration of check(). The 2is then passed all the way down the stack to the original call inside the main, eventually ending up on your Console window. See this reference
[printf returns the] number of characters transmitted to the output stream or negative value if an output error or an encoding error (for string and character conversion specifiers) occurred.
Consider the following code. It exhibits identical behaviour to your posted code.
#include <stdio.h>
int check(int c)
{
int ret = 0;
c = c + 1;
if (c < 6)
{
ret = check(c);
return ret;//helps inspect ret
}
//looks like the compiler inserts that return statement
ret = printf("%d\n", c);// 2 <- number of characters in "6\n".
return ret;
}
int main()
{
int c = 0;
int ret = 0;
ret = check(c);//ret comes out == 2. This is the return value of printf
printf("%d\n", ret);
getchar();
return 0;//don't forget this guy!
}
Disclaimer: Even though it appears that this is what is happening, and most likely it probably is, It is not a shortcut and I would not count on this happening every time. The behaviour is still undefined! The best thing to do is to return from functions normally.

An Address is Printed Instead of the Expected Value

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

How do you explain the discrepancy in the output of this piece of code?

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.

C return value is displaying some bizarre behavior

A fair warning — I'm very new to C, and there's some unpredictable behavior. I'm not sure how to begin troubleshooting this.
I'm trying to solve one of the early Euler problems (to do with numerical palindromes) and I'm having trouble with my check function. When a number a is passed through rev(a), everything works as it should. When passed through ret(a) (a function which will eventually check for equality, bool type, etc), it returns totally wrong number — something to do with memory, I think. Can anybody help me, please?
#include <stdio.h>
#include <stdbool.h>
int rev(int a);
int check(int a);
main() {
int a = 12;
printf("%i ", a);
printf("%i ", rev(a));
printf("%i\n", ret(a));
}
int ret(int a){
return rev(a);
}
int rev(int a){
int b;
while (a>0){
b = (b*10) + a%10;
a/=10;
}
return b;
}
In rev, the first iteration of the loop
int b;
while (a>0){
b = (b*10) + a%10;
operates on an uninitialised value of b. This makes the end result unpredictable and almost certainly wrong.
The fix is pretty simple - you just need to initialise b to 0
int rev(int a){
int b = 0;
// function unchanged beyond this
If calls to rev worked for you, this was just luck (either good or bad, depending how you look at it). Reading the content of uninitialised memory can have any effect, including the stack for b just happening to be set to 0. You'd probably have found that changing platform or compiler flags caused things to break.

Resources