Output is not giving garbage value - c

Good evening guys,
This is a little program shown below. I'm seeking for garbage value of b in every execution, but get the same answer.
The code is simple as follows:
#include<stdio.h>
#include<conio.h>
int main(void)
{
int a = 300, b,c;
if (a>=400)
b=300;
c=200;
printf("\n%d\n%d",b,c);
getch();
}
The o/p in Codeblocks is as follow
2
200
but if I remove the line
b=300;
keeping the semicolon, then it gives garbage values.
Why is this contradiction happening?

Reading uninitialized variable follow below rules,
Static variable are by default initialized to zero means local static or file scope variable (global one).
Non-static variables which local to function are indeterminate. Reading them prior to assigning a value results in undefined behavior. compiler is free to do any thing. It can be zero, it can be the value that was in there, it can crash the program. you have absolutely no guarantees.
It will simply give you the last value that was stored in that position on the stack (or in that register if the variable happens to be stored in a register).
Also undefined might be different between different compilers.

Here 2 is garbage only, you should print the value of b before 'if-statement' and see if it matches with the last print statement. If it matches then both are garbage values and no change occurred to them because of the 'if-statement'.
The question about how compiler generates a garbage value is unpredictable/random.

Explanation:
Step 1: int a = 300, b, c; here variable a is initialized to '300', variable b and c are declared, but not initialized.
Step 2: if(a >= 400) means if(300 >= 400). Hence this condition will be failed.
Step 3: c = 200; here variable c is initialized to '200'.
Step 4: printf("%d, %d, %d\n", a, b, c); It prints "300, garbage value, 200". because variable b is not initialized.

Related

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:)
}

variable not declared in for loop condition in C-still works

I wrote the below code to find the sum of all digits in C, and when I compiled and ran it, it was successful.
But, only later I realized that i had not entered any value for the variable 'n' in the for loop's condition.
I'm confused on how this program works, even when there is no value assigned to the condition variable.
I would like to be clarified of the same.
#include<stdio.h>
void main()
{
int no,a,b,n,sum=0;
printf("Enter the number to be added");
scanf("%d",&no);
for(int i=0;i<n;i++)
{
a=no%10;
b=no/10;
sum=a+sum;
no=b;
}
printf("The sum is %d",sum);
}
I'm confused on how this program works
Well, "works" is a very poor observation / decision here. This is undefined behavior.
You're attempting to use the value of an automatic local variable n while it is indeterminate. This invokes the UB.
To quote the C11 standard, chapter ยง6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate. [...]
So, in your case, n meets the criteria described above, and hence the content is indeterminate.
Now, after that, in case you try to use a variable while it holds indeterminate value and either
does not have the address taken
can have trap representation
the usage will lead to undefined behavior. That is exactly the case here.
That said, for a hosted environment, the conforming signature of main() is int main(void), at least.
An uninitialized variable MUST contain some value - every address in a computer must have some combination of 1's and 0's even if those values are useless. Therefore it is given a random one when first created if you do not initialize it to something yourself. Often it isn't even "given" data so much as it "takes on" whatever value was at the address it was given to live at when created, but different environments will handle this "non-initialization" differently. You are essentially getting lucky right now under your current conditions.
For that reason this kind of code is considered to have undefined behavior because you are not guaranteed to get lucky like that in every situation. Be safe and always initialize values for variables because this can be a hard thing to catch later when code that used to work suddenly doesn't.
n is not initialized, so is worth anything present at the allocated memory location when run. So if you're lucky, after a few iterations no is 0 and the result is correct but it's just luck.
In your case, you don't need n, just stop when division yields 0 (that's probably why you forgot to initialize n)
while(no!=0)
{
a=no%10;
b=no/10;
sum+=a;
no=b;
}

Why a syntax like "a=b--- // a newline, line ends without ;" does not produce syntax error?

What is the output of this program and how?
#include<stdio.h>
int main(){
int a=0,b=10;
a=b---
printf("the value of b=%d",b);
printf("the value of a=%d",a);
return 0;
}
In your code, writing
a=b---
printf("the value of b=%d",b);
is same as
a = b---printf("the value of b=%d",b);
which is an expression with undefined behavior, as an attempt is made to change and use the value of variable b in two subexpressions without a sequence point in between. Hence, the output of this code cannot be justified.
Without the above problem, in general, the syntax is similar to
x = (y--) - (<return value of printf() call>)
which is a perfectly valid syntax.
Note:
Why a = b---<something> is treated as a = (b--) - <something> and not a = b - -- <something> is due to the maximal munch rule.
Strictly speaking, as others have said since this is undefined behaviour, the result could be anything . And while they're right, it doesn't explain why you get this specific answer in this specific compiler.
In practice b will usually be printed as 9, or 10 depending on whether the compiler does the decrememnt first or the printf first.
printf returns the number of characters printed. Which I think is 16 or 17 in this case.
So this is like writing a = (b--) - 16; b is 10 before the decrement and it's a post decrement so this is the value used.

using statement bodies in printf in C

I am taking a course where we were doing a lot with systems level programming, and now we are getting to the point where we are starting the introduction to C. We are given some code and told to state the values printed out by each 'printf' statement. I know how to do regular printing statements in languages like Java and Python. But the code given has bodies to the print sections which I have not seen before. The statements are executed in the order A, B, C, D. Here is the code:
int t; /* This variable is global */
{
int t = 2;
printf("%d\n", t); /* A */
{
printf("%d\n", t); /* B */
t = 3;
}
printf("%d\n", t); /* C */
}
{
printf("%d\n", t); /* D */
}
The part that confuses me is that some of the print statements have bodies. A print statement inside a print statement?
So here is what I am thinking: t = 2 so when we get to A, it executes the body within A first. So the first statement in that body is to print t which at this point is 2. Then after we print 2, we change the value in t to 3. After that we go to C which just prints t which is 3 (I guess? I'm not sure here). After that we go to the body that contains D. Int t is a global variable declared above, but it is never initialized (except in the first portion of code). So in the second portion that contains D, would there be an error since t is not initialized in that block of code?
2
3
3
Error
I feel like I am wrong.
First, you have a global variable t, which is initialized to 0 (AFAIK, all global variables in C are initialized to 0 if not explicity initialized)
Then, a block is opened and a local variable t is declared and initialized to 2, which shadows the global variable with the same name (in java this is an error, the compiler will complain and refuse to use the same name), for the whole block.
The first printf, which is inside the block, prints 2.
Then a nested block opens, with a printf in it. This printf will also use the local variable t, printing 2 again.
Then t is assigned 3. This "t" cannot be other than the local variable.
Then, the nested block closes and we are back into the first still opened block in which local t was declared. The printf here prints 3.
Then the first block finishes and so the local variable t is gone. A new block opens and the last printf prints the value of global variable t, which is the only one known in this block. It prints 0.
The curly braces begin and end new scopes, just like they do with functions.
There are two "main blocks" in your program. One contains a definition of variable t, thus shadowing the global t. Therefore 2, 2, and 3 is printed out. The second block can access the global t, so the printf in the second block prints out the value of the global t.
Global variables are initialized to 0 by default, so the last printf call prints 0 to the screen.
Local variables are not initialized with any value, so the last printf call would yield undefined behavior.
The output is
2
2
3
and after that
0
if the "global" t really is global or (probably1) some random value if it is local.
1 Undefined behavior occurs. Anything may happen. In this case, it's probably a random value getting printed out.

Variable inside if block is assigned to zero even if the if expression evaluates to false in C

#include<stdio.h>
int main(void) {
int a = 123,b,c;
if(a>300) {
b=200;
}
c=4556;
printf("b = %d\n",b);
return 0;
}
Now as if block evaluates to false so if block should not get executed, but the code is printing value of b as 0.
Moreover if the value of c isn't assigned after the if block is over then the code shows some garbage value for b.
Can anyone tell me why is this happening like this, as far as I know b must show some garbage value for the first case also.
Unless you initialise your variables, you will not know for sure what their values are so this is not remotely surprising. If you want your b variable to contain a meaningful value, then initialise it with that value.

Resources