Unable to understand the output of C progaram [duplicate] - c

This question already has answers here:
sequence points in c
(4 answers)
Closed 9 years ago.
My code is :
#include<stdio.h>
int main()
{
char c='8';
int d=8;
printf("%d %d %d",d,d+=c>='0'&&c<='9',c++);
return(0);
}
The output of this question is : 9 9 56.
I'm unable to understand this.
Please somebody help me and please explain me the output.
Thanks.

You are observing undefined behaviour. d is passed as an argument twice, and once with side effects. If done in sequence your code should be equivalent to
char c='8';
int d=8;
printf("%d",d);
d+= (c>='0)' && (c<='9');
printf(" %d", d);
printf(" %d",c);
c++;
But since it is undefined in what order the arguments are computed when passing them with side effects to a function you are seeing here:
char c='8';
int d=8;
d+= (c>='0)' && (c<='9');
printf("%d",d);
printf(" %d", d);
printf(" %d",c);
c++;

Basically printf reads the argument from right to left so the first print would be of
" printf("%d %d %d",d,d+=c>='0'&&c<='9',c++); "
- 1st output = c++ -> which is nothing but ascii value of '8' = 56
and then c is incremented by 1 .
- next is the d -> it boils down to d = d + if(c>='0'&&c<='9') ...
so d = d+1 so 9 here
- next d again so it is again Hope it is clear !

Ok, the first thing you have to know is, a char is stored in the memory as Ascii Table. So in the memory the char c will have a integer value of '8'. From the table we know that the integer value of '8' is 56. According to the table we'll get:
'8': 56
'0': 48
'9': 57
So let's get started.
c++: It is a statement which adds c by one and return the value of current c.
Example:
int a,c;
c=1;
a=c++;
printf("a=%d,c=%d",a,c);
The result of this code is "a=1,c=2"
so %d of c++ is still 56.
d+=c>'0'&&c<='9': According to C's priority this statement will be like:
d+=(c>'0'&&c<='9')
So let's start with c>'0'&&c<='9' first. It is a condition statement. Is c's Ascii value great or equal to 0's Ascii value AND less or equal to 9's Ascii value?( Notice c's Ascii is 56 or 57 now because the evaluation order of printf is undefined. So it will be 56 if this statement is evaluated before c++ or 57 if after c++. But both way, c<='9' is true ) YES. So the statement is true. In C the TRUE is 1.
So d+=c>'0'&&c<='9' will be d+=1 which means d=d+1. So %d of d is 9.
So the result is "9 9 56"

Related

printf statement modification in C [duplicate]

This question already has answers here:
Can we use only one variable for many format descriptors in printf in C
(3 answers)
Closed 1 year ago.
Lets take an example: (in C)
consider we have inputted a,b; (say a=1,b=2)
expected output:
1 + i2
1 - i2
1 X i2
so i do
printf("%d + i%d \n %d - i%d \n %d X i%d ",a,b,a,b,a,b);
Here Iam using a,b 3 times in printf statement ,the same variable is being defined 3 times
This is a small example so only 3 times we are using a,b but in big problems this thing might become a tedious job.
so is their a better way or alternative way to do this ?
You can split your printf function into few printfs , as it will reduce the work of matching the number of format specifiers and the variables.
By the way , I think you could use a loop structure to reduce that further.
Maybe use this: (the character array a contains +,- and X. The for loop is to display the characters contained in a)
#include<stdio.h>
int main(int argc, char *argv[]){
char a[]="+-X";
int n1=1;
int n2=2;
for(int i=0;i<3;i++){
printf("%d %c i%d\n",n1,a[i],n2);
}
}

Simple 'if' statement in C not performing as expected when comparing int to char

I'm new to C and have gotten stuck on something that must be very basic.
I have 2 char arrays and am calculating the absolute difference between elements of the arrays in an 'if' statement. However, the 'if' statement is not evaluated as I would expect. I am getting values printed where the difference is not greater than 1.
Is this something to do with the abs function returning an int which I then compare to a char?
Any suggestions?
if(abs(arr1[i] - arr2[i]) > '1')
printf("%c ", arr1[i]);
printf("%c ", arr2[i]);
printf("%d diff\n", abs(arr1[i] - arr2t[i]));
'1' is not same as 1. '1' is equivalent to numeral 49 from ASCII table.
So make the comparison against integer 1 in your case
if(abs(arr1[i] - arr2[i]) > 1)
Also your if block does not include all the lines below. Enclose the statements which need to have effect of if condition with {}.
if(abs(arr1[i] - arr2[i]) > 1)
{//Add braces to enclose multiple statements
printf("%c ", arr1[i]);
printf("%c ", arr2[i]);
printf("%d diff\n", abs(arr1[i] - arr2[i]));// arr2t[i] -> arr2[i] seems to be a typo
}
Lets take a look at an ASCII table. The value for e.g. '2' is 50, and the value for '1' is 49.
Now what happens when you do '2' - '1'? What is the result of that? It's 1, not 49.
So your comparison should be against the integer 1 and not the character '1'.
And as mentioned, you're missing a block {} for the printf calls.
Your mistake is by comparing the int to a char.
You see, every char is displayed to the user as a char, but in the memory is represented as an int, the ASCII code of that char.
In the same manner, you can create a char this way:
char c = 49;
and it will be the char '1'.
So when you compared it to the char '1' the compiler thinks you meant the ASCII code of the character 1, which is 49 (you can see that if you type ALT + 49 in numpad).
Just compare the result of the subtraction to the int 1 and you will be fine.

Why isn't modulo operator working inside printf function in C?

When I remove "%97" then code works and prints what it expected. Like if input is "a" then it prints "f" whereas it doesn't works when that modulo 97 is present and prints whitespace.
What is reason behind this problem? How to solve it?
int main(void)
{
char *s = get_string();
for(int i = 0; i<strlen(s); i++)
printf("this is %c", (s[i]+5%97));
}
Edit : Guys after adding brackets i.e. changing my last line to "(s[i]+5)%97" program isn't working as expected. Upon entering "a" output should be "f" but it's whitespace.
Upon entering "A" I am getting "F"!! What's happening? This program is meant to convert "a" to "a+5" but it's converting "A" to "A+5". Please explain.
I think you want to write:
(s[i] + 5) % 97
The expression you wrote:
s[i] + 5 % 97
is the same as:
s[i] + (5 % 97)
That is, the operator % has a higher precedence than +.
You are adding 5 % 97 which is 5 to s[i] in your code.

Unexpected behavior of printf() in C [duplicate]

This question already has answers here:
what does the - operator do with char *?
(4 answers)
Closed 9 years ago.
#include <stdio.h>
int main()
{
short int a = 5;
printf("%d" + 1, a);
return 0;
}
The code prints the alphabet enclosed in quotes in printf irrespective of the value and type of variable a. If any other number is added except 1 nothing gets printed.
Why is it so?
Not sure, I would expect it to print just d, of course. That's what happened when I tested it.
If you add more than 1 (or 2) all bets are off and you're getting undefined behavior for passing a random pointer instead of a valid formatting string.
On compiling the above code, you should get a warning like:
[Warning] too many arguments for format [-Wformat-extra-args]
Now remove the printfs argument a.
printf("%d" + 1);
This will print d.
100 101
% d
^
|
Here is the starting address of the string.
%d is a string and its starting address is 100. "%d" + 1 will give you the address 101.
Why you want to do this?
if you want you can do like
do like
printf("%d", a+1);
Try this and you'll understand what unwind is trying to make you understand
#include <stdio.h>
int main()
{
short int a = 5,b = 4;
printf("%d %d" + 4, a,b);
return 0;
}
OUTPUT: d
Since it takes the 4th character inside the double quotes in printf() statement..
If number is 3
OUTPUT: 5
If number is 2
OUTPUT: 5
If number is 1
OUTPUT: d

Explain the following code snippet?

int main()
{
int a, b, c;
a = 10;
b = 20;
c = printf("%d", a) + ++b;
printf("\n%d", c);
}
The output of the above program is 23 it seems but i dont know how it is obtained. Can anyone have an idea about it?
printf has a return value, which is the total number of characters it prints.
The statement printf("%d",a) will print 10, which means the return value of printf here is 2.
The rest is easy:
c=printf("%d",a)+ ++b;
c will have a value of 2 + 20 + 1, which is 23.
Here the output will be two different integers,for two different printf statements . For the first printf statement the code prints 10, then when this printf statement participate in some assignment statement , it is treated as the number of characters it is printing i.e. 2 here. Then it is added to ++b i.e. 21 (PRE-INCREMENTED) . So the output is 23(2 + 21) .
The whole output looks like this :
10
23
printf returns the number of characters printed as an integer. So as you are printing 10 it will return 2.
So now
c=printf("%d",a)+ ++b;
will become
c=2+ ++b;
since b with a value of 20 is pre-incremented this will become
c=2+21
Therefore c=23

Resources