main(){
int a[5]={1,2,3,4,5};
int *ptr=(int *)(&a+1);
printf("%d %d",*(a+1),*(ptr-1));
}
The output of this code is coming out to be : 2 5 .
I understand why 2, but why 5 is coming for *(ptr-1)?
Also ,
main(){
while(1)
{
if(printf("%d",printf("%d")))
break;
else
continue;
}
}
This code is showing the output as : Garbage value . How and why?
printf() function returns an integer. Upon success, the return value is number of character written. And upon error, the return value is negative.
since the printf("%d") (inner one of printf("%d",printf("%d"))) will be executed first, it will most likely show some random value of a memory location. After that printf("%d",printf("%d")) will print number of values written during the previous call.
Example: 123456789010
Related
#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.
I have written the following code
#include <stdio.h>
void recurse();
int main()
{
recurse();
return 0;
}
void recurse()
{
static int n=987654321;
if(n==0)
return ;
printf("%d",n%10);
n=n/100;
int a=n;
recurse();
if(a!=0)
printf("%d",a%10);
}
I am not understanding why the output is coming 135799753?
What I thought the answer to be was 135799 because after printing the first 9 after 1357 n will become 9 and hence n/100 will be zero so the recurse function will return to the main without printing anything.
Please correct me where I am wrong.
Thanks in advance!!
Output of program is correct. Your output also consists of these values -
if(a!=0)
printf("%d",a%10);
Value of a is also printed if it is not 0. But the values are printed from last to first because of these statements after the recursion call.
You consider output to be 135799. Second 9 being value of a%10 but value of a%10 from previous recursion calls is also to be printed as those statements get executed after the end of recursion call.
You can see in this example.
I have done my fair share of studying the C language and came across this inconsistency for which I cannot account. I have searched everywhere and reviewed all data type definition and relational syntax, but it is beyond me.
From the book C How to Program, there is a question to make a binary to decimal converter where the input must be 5-digits. I developed the follow code to take in a number and, through division and remainder operations, split it into individual digits and assign each to an element in of an array. The trouble arises when I try to verify that the number entered was indeed binary by checking each array element to see whether it is a 1 or 0.
Here is the code:
#include <stdio.h>
int power (int x, int y); //prototype
int main(void)
{
int temp, bin[5], test;
int n=4, num=0;
//get input
printf("%s","Enter a 5-digit binary number: ");
scanf("%d", &temp);
//initialize array
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
//verify binary input
for (test=4; test>=0; test--){
if ((bin[n]!=0)&&(bin[n]!=1)){
printf("Error. Number entered is not binary.\n");
return 0; }
//convert to decimal
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
printf("\n%s%d\n","The decimal equivalent of the number you entered is ",num);
return 0;
}
//function definition
int power(int x, int y)
{
int n, temp=x;
if(y==0) return 1;
for(n=1; n<y; n++){
temp*=x; }
return temp;
}
Could someone explain to me why regardless of input (whether: 00000, or 12345), I always get the error message? Everything else seems to work fine.
Thank you for your help.
Update: If the if statement is moved to the while loop before. This should still work right?
Update2: Never mind, I noticed my mistake. Moving the if statement to the while repetition before does work given the solution supplied by sps and Kunal Tyagi.
After this
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
n is set as -1 so when you try to convert to decimal the statement bin[n] is actually bin[-1] so it returns you error.
One issue is that, while checking if the number is binary or not, you are returning at wrong place. You need to return only if the number is not binary. But you are returning outside the if condition. So your program returns no matter what the input is.
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1))
printf("Error, numbered entered was not binary.\n");
// Issue here, you are returning outside if
return 0; } //exit program
You can change that to:
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1)) {
printf("Error, numbered entered was not binary.\n");
// Return inside the if
return 0; // exit program
}
}
There is one more issue. Before you convert your number to decimal, you need to set n = 0;
//convert to decimal
n = 0; /* need to set n to zero, because by now
n will be -1.
And initially when n is -1, accessing
bin[-1] will result in undefined behavior
*/
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
This looks like a homework, but your issue is in the brackets. More specifically line 23. That line is not part of the logical if statement despite the indentation (since that doesn't matter in C).
No matter what, the program will exit on test=4 after checking the condition.
Solution:
if ((bin[test]!=0)&&(bin[test]!=1)) { // << this brace
printf("Error, number entered was not binary.\n");
return 0; } } //exit program // notice 2 braces here
// Define the recursive function.
int collatz(int p1)
{
// While Loop Starting
while (p1>1)
{
//when the number is even
if(p1%2==0)
{
p1 = p1/2;
printf("%d ", p1);
//using recursion
return collatz(p1);
}
// Case where number is odd.
elseif
{
p1 = 3*p1+1;
//print function
printf("%d ", p1);
//using recursion
return collatz(p1);
}
}
}
// Main body.
int main()
{
// Declare the variable and initialized it.
int p1= 4;
//print function
printf("User Entered value : %d\n", p1);
// Display the number
printf("%d\n", collatz(p1));
//End
return 0;
}
Output: I am getting the Output as :
2 ,1, 1
I should not get the last number 1 repeated.Could you please correct me where i have done mistake.Please do the needful.
You should always enable warnings when you compile a C or C++ program. Had you done do, the compiler would have warned you that your function collatz could terminate without returning a value. (What happens if the argument is 1?)
That's undefined behaviour, and so is the use of the possibly-nonexistent return value in your main function.
So it is just a quirk of chance that it happens to print 1 in main. But whatever it printed would be wrong because you seem to expect the output to be limited to what is printed in collatz.
You might try playing computer and executing your function with a pencil and paper. It won't take very long. Of course, you could also use a debugger.
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.