How come the output of this C program is 1? - c

#include <stdio.h>
int main() {
unsigned char c = (int) 0.54;
for(; c++; printf("%d", c));
printf("%d", c);
return 0;
}
And when I run the program the output is displayed as 1
How can the output be 1? Thanks in advance

In the first line- unsigned char c=(int)0.54; char actually stores the ASCII code of the character so in another way it's an integer which stores the data in this way :
The compiler converts the number stored into the character from decimal number system to binary number system and takes into consideration only the first 8 bits from the right of that number represented in binary.(we don't need to consider the case of negative numbers since you use an unsigned char)-so as a result the variable c takes 0 as value at the end of this line.
For the second line of your code- for(;c++;printf("%d",c)); :
so we have a for loop
( for (INITIALIZATION; CONDITION; AFTERTHOUGHT))
** In the INITIALIZATION part , Leaving this empty is fine, it's just equivalent that you have already initialized the variable that you are going to use as loop variable .
** In the CONDITION part , c++ is equivalent to c++!=0. It keeps the for loop running until c++==0.(in your case c is initialized by 0 , so we will have c++=0 and the program immediately exits the for loop).
** In the AFTERTHOUGHT part , The printf is run at the end of each iteration but doesn't change the value of c.(since the condition c++!=0 is not verified the code will not write the iteration, so it will not pass to printf)
printf("%d",c); will display 1 ( c++ in your loop is used as condition and in the same time to increment variable c by 1 ; c++ post-increment operator uses the principle 'use-then-change' so , c is incremented by 1 exactly after exiting the for loop , and c becomes equal to 1).

Related

What will be result of code execution? C Operator Precedence

I have a problem with predicting result of code linked below.
Why program is printing 2 0 6 0 10 0 16 0 20 0 ? I guess it is all about operators precedence, but after thinking a while I can't realize what's wrong with my interpretation. Can you explain it a little bit?
#include <stdio.h>
int main(void)
{
int tab[10] = {2,4,6,8,10,14,16,18,20};
int *pi, i;
for(pi = tab; ++pi < tab+9;)
{
*pi++ = 0;
*pi *= 2;
}
for(int i=0; i<10; i++)
printf("%d ", tab[i]);
return 0;
}
The first thing that the for loop does is point pi at tab, i.e. pi=&tab[0]
So pi is pointing at the number 2. The next piece of code to be executed is the for loop's "condition" statement ++pi < tab+9. This first increments pi (so it's now pointing at the number 4 in tab[1]) and checks whether it's still pointing at a member of tab earlier than the final 20.
In the body of the for loop, the line *pi++ = 0; first stores a 0 at the address pointed to by pi (which means that tab[1] is now 0 rather than 4) and then (post-) increments pi to point at tab[2], which is 6. Then the line *pi *= 2; doubles the value pointed to by pi, so tab[2] becomes 12.
The next thing that happens is a re-evaluation of the for loop's conditional statement (since its iteration statement is empty): pi is incremented and checked.
The rest of the iterations are fairly uneventful. The final state of tab is that the first member is unchanged, members with an odd index are zero, and other members are doubled from their initial value.
General advice regarding operators and precedence: one of two situations is almost always the case. The first is that you and the compiler don't agree on the order in which the operators in your code will be applied—in other words your code doesn't do what you expect. The second is that you understand perfectly what the compiler is going to do, but the programmer reading your code does not—in other words your code doesn't do what they expect. Fortunately, both situations can be mitigated by adding parentheses to remove any doubt.
The actual output is 2 0 12 0 20 0 32 0 40 0 (as shown in Blastfurnace comment https://ideone.com/UUy8QO)
pi is indeed initially on the first cell, but your stop condition increment the pointer. Therefore, inside the loop, for the first instruction, pi is in tab[1]. It first put this cell to 0, then increment with ++. On the second line, it double the value, therefore it double tab[2]. Then, the stop condition again increment the pointer, and so on.

What is happening here while post/pre decrementing a char variable in C [duplicate]

This question already has answers here:
What is the difference between ++i and i++?
(20 answers)
Closed 4 years ago.
I was solving some multiple choice C codes from a book. Two of the questions involve pre decrementing, post decrementing a char variable initialised at 0. The output for both these is very different. I dont understand whats going on there.
Code 1
char i=0;
do
{
printf("%d ",i);
}while(i--);
return 0;
The output for this snippet is 0.
Code 2
char i=0;
do
{
printf("%d ",i);
}while(--i);
return 0;
The output is for this one is
0,-1,-2,.....-128,127,126,......1 .
Can anyone explain why this is happening?
At both code while loop checking i==0 or not. If i!=0it will keep going on.
At first code value of i initially 0. So after printing 0 it checks i==0 or not. if i==0 it will break the loop or keep going on by decrementing i. So in code 1 post decrementing used. check value first then decrements the value.
At second code value of i initially 0. So after printing 0 it decrements i then it checks if i==0 or not. it is pre decrement. decrement value first then check.
Here, i is char which size is 1 byte and range -128 to 127. So after decrementing value 0 to -1 it keep decrementing until it goes to 0 and exit the loop by printing 0,-1,...,-128,127...1 .
Code 1
char i=0;
do
{
printf("%d ",i); // print o
}while(i--); //check i = 0, means false, loop ends, then increment i
return 0;
Code 2
char i=0;
do
{
printf("%d ",i); //print 0
}while(--i); //decrement i, check i=-1, means true, next cycle, loop until i = 0 which means false
return 0;
Both i-- and --i are expressions. An expression is (part of) a statement that can yield a value. As per definition, the pre-increment version increments first, then yields the value. For the post-increment version it is the other way round.
This is completely independent of whether the expression is used in a while statement or elsewhere. However, when using such expressions, you need to be aware of operator precendence.
Initial value of i is 0.
In Code 1, first while check happens in which the value of i (= 0) is used and then i is decremented because it is postfix decrement. So it exits while after printing 0.
In Code 2, because it is prefix decrement, i is decremented first and its value (= -1) is used when the while check is performed. Here it exits after printing the entire range of values a signed char can hold because it becomes 0 at the end only.

codeblocks gives incorrect result as output

My code :
#include <stdio.h>
int main(){
int a = 5;
int b,c;
if (a==4){
b = 6;
c = 7;
}
printf("%d %d\n",b,c);
}
I know result should be 0 0, but codeblocks giving answer 50 8. I tried online compiler and I got answer 0 0. So what is problem with codeblocks? I am using latest version of codeblocks and gcc c compiler. How can I avoid this kind of problems in future?
The values of b and c variables are garbage because if() condition become false. It means, it is undefined behaviours.
C11 section 6.7.9 Initialization :
Paragraph 10:
If an object that has automatic storage duration is not initialized
explicitly, its value is indeterminate.
I know result should be 0 0
Your guess is wrong
The variables b,c are automatic (storage specifier), uninitialized variables -> indeterminate values -> no guarantee on their values -> UB!
In your case you got 50,8 you might as well get other values / print garbage/ crash...
The values for b and c are undefined in this program as they dont get initialised before they get printed
Okay looking at your code and analyzing it step by step,
#include <stdio.h>
int main(){
int a = 5;//You've assigned the value of 5 to integer a.
int b,c;//You've declared two integer variables "b" and "c".
if (a==4)/*Compiler checks whether the if condition is true,which in your case is not*/
{
b = 6;/*Assigning value 6 to the b variable but no effect as the if condition of your's is not satisfied*/
c = 7;/*The same above condition applies here.*/
}
printf("%d %d\n",b,c);/*Here your trying to print the values of b and c,
But remember you have not given them any value. So the compiler automatically prints the garbage value(random value). It need not be 0 all the time.*/
return 0;//You forgot this step btw:)
}

Count length and number of words in string

I am a beginner in C. I am trying to print out the length and the number of words in a string inputted by user. I have trouble dealing with the counting of words. I attempt to scan the number of the space character , then add 1 to the result. It is guaranteed that each word is only separated by one space.
I executed the code, and inputted
I go to school by bus.
The second output was not as I expected
22
24
22 is correct since it is indeed the length of the string, but I do not understand why it prints 24 instead of 6 (result of 5 spaces plus 1).
The code is as follows
#include<stdio.h>
#include<string.h>
int main(){
char in[256];
int cl=0,cw,i;
scanf("%[^\n]",&in);
cw=strlen(in);
for(i=0;i<=cw;i++){
if(in[i]=' '){
cl=cl+1;
}
}
printf("%d\n",cw);
printf("%d\n",cl+1);
return 0;
}
What went wrong, and how can I get a correct output?
if(in[i]=' '){
will always be true, you need to change it to
if(in[i]==' '){
2 mistakes I see in your code.
if(in[i]=' ') should be if(in[i]==' ')
== Checks if the values of two operands are equal or not. If yes, then the condition becomes true.
= Simple assignment operator. Assigns values from right side operands to left side operand.
i<=cw should be i<cw
indexing starts with 0 in C.
As Pras said, on ifs you normally use ==, because you are comparing and it returns true or false
If you just use = it attributes (insert) a value on the right to the left.
You should use == instead of = in the if statement that detects the space.
The assignment operator, = gives is always true if the number is asssigned to a nonzero value.
The equivalence operator, == is what actually compares whether two numbers have the same value.
It may be surprising that the assignment operator can actually test whether or not a number is zero(at least on x860. This is because jz, one of the testing instructions, checks something called a flag register (a special memory location) that contains information about the arithmetic operation most recently executed. == does a cmp, which subtracts both numbers from each other to see if it is 0. Jz stands for "jump if zero", so two equal numbers result to the "jump" to the instructions in the if statement. When = is used, the compiler uses jz instead (in order to comply with the c idea that nonzero number in if is true), which results in the behavior described above.

Understanding the basics of the for loop in C language

can anyone explain the working of the for loop in the following code:
#include<stdio.h>
#include<conio.h>
int main()
{
char i=0;
for(i<=5&&i>=-1;++i;i>0)
printf("%d\n",i);
getch();
}
Let's break the for statement down, we have three phases, the initialiser, the test, and the modifier:
for(<Initialiser>; <Test>; <Modifier>)
<content>;
In your case:
for(i<=5&&i>=-1;++i;i>0)
// initialiser: i<=5&&i>=-1;
// test: ++i;
// modifier: i>0
The initialiser is done first. Here no assignment is done. Two boolean expressions (denoted by the >= and <= operators are compared in a logical &&. The whole initialiser returns a boolean value but it doesn't do anything. It could be left as a blank ; and there would be no change.
The test uses the pre-increment operator and so returns the result of i+1. If this result is ever 0 it evaluates as false and the loop will terminate. For any non-zero value it evaluates to true and continues. This is often used when i is initialised to a value less than zero and so the test will increment i until i+1 results in a zero, at which point the loop terminates.
Finally we have the modifier, which in this case simply uses the > operator to evaluate to a boolean value. No assignment is done here either.
The fact is that you've gotten the test and the modifier confused and put them in the wrong positions but before we sort that out let's see how it would work…
We begin with:
char i = 0;
…and for all intents and purposes this does the same thing as our for loops initialiser would do in normal circumstances. The next thing to be evaluated is the for loop's initialiser:
i<=5 && i>=-1;
Because i is 0 it is less-than-or-equal-to 5 and it is greater-than-or-equal-to -1. This expression evaluates to 1 but nothing is done with that value. All we've done is waste a bit of time with an evaluation.
Next up is the modifier to test whether or not the for loop's inner block should be executed:
++i;
This evaluates to 1 and also assigns that value to i. Now, as it's evaluated to a non-zero number, the loop executes:
printf("%d\n",i);
And the digit 1 is printed to the screen... Now it's the modifier that gets executed:
i>0
Well, i is 1 so that is greater-than 0. This evaluates to 1 (or true). Either way, this is ignored. The purpose of the modifier isn't to test or check anything. It's there so that you can change the state of the program each time the for loop iterates. Either way, the loop repeats and it will do this for a very long time. Why? Because ++i is going to evaluate to a non-zero number for a while. Whether or not it will ever terminate depends on how your system deals with integer overflows.
This is what you meant to do:
#include<stdio.h>
#include<conio.h>
int main()
{
for(char i=0; i<=5&&i>=-1; ++i)
printf("%d\n",i);
}
Do you see the difference? Our initialiser now starts the loop with the state of i as zero. We then test if it's within the bounds of -1 to 5 and each time we iterate we increment i by 1. This loop will output:
0
1
2
3
4
5
This snippet:
for(i<=5&&i>=-1;++i;i>0)
printf("%d\n",i);
Does the same as this:
i<=5 && i>=-1; //statement with no effect
while(++i)
{
printf("%d\n",i);
i>0; //statement with no effect
}
So, it's going to print i until ++i evaluates to 0. This will happen after i overflows and becomes negative, then incrementing towards 0. That will take 255 iterations to happen, since chars can store up to 256 different values.
for ( variable initialization; condition; variable update ) {
}
the variable initialization phase is done only once when the for loop starts.
the condition is checked everytime before running code inside the loop. if the condition is false then the loop is exited.
the variable update is done after the first iteration, from the second iteration it is done before the condition check.

Resources