Using a variable in its own declaration in recursion [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Using a local variable in its own initialization usually has no effect but doing it with recursion causes strange values. Why is there undefined behavior in the recursion but not outside of it?
#include <stdio.h>
void recurse(int count);
int main()
{
int j = j + 1; // a weird thing to do but its just 1
printf("%d\n", j);
j = j + 1;
printf("%d\n", j);
j = j + 1;
printf("%d\n", j);
recurse(1);
printf("\n");
}
void recurse(int count){
int i = i + 1; // the really weird part
printf("%d ", i);
if(count < 10)
recurse(count + 1);
return;
}
Output:
1
2
3
32737 1 32737 1 1 1 1 1 1 1
The large numbers are not always the same for each execution.

This is an example of undefined behavior.
Because the value can't be known before it is assigned, you can't predict what will happen. Running the same code on a different machine, or compiled with different settings, can yield different results.

Local variables (not initialized) have indeterminate value in C.
Reading them prior to assigning a value results in undefined behavior.
Nice quote from wikipedia article
In computing, an uninitialized variable is a variable that is declared
but is not set to a definite known value before it is used. It will
have some value, but not a predictable one. As such, it is a
programming error and a common source of bugs in software.
However, it is important to mention that in C, static and global variables not initialized will have the value = 0.

Related

Why different behaviour of same code by different compilers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
This is code written by me where I have to print a single integer denoting the minimum possible capacity of a tram (0 is allowed). It's a problem from codeforces. The answer in CodeBlocks is showing 6 (the right answer) but in codeforces compiler I'm getting another output.
Why is this happening?
#include <stdio.h>
int main() {
int n, i, j, max = 0, sum = 0;
int pssnger_left;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &a[i][j]); // declaring the value of array
}
}
pssnger_left = a[0][0] + a[0][1];
for (i = 1; i < n; i++) {
sum = pssnger_left - a[i][0];
sum = sum + a[i][i];
pssnger_left = sum;
if (max < sum)
max = sum;
}
printf("%d", max);
}
Input:
4
0 3
2 5
4 2
4 0
Output:
4221555
Answer:
6
Checker Log
wrong answer expected 6, found 4221555
Here is the link of the problem: https://codeforces.com/problemset/problem/116/A
Different compiler, different answer, 99% of the cases is explained by Undefined Behaviour, UB.
In the shown code here it is a[i][i];.
For any i > 1 that is not what you want it to be
and for most high i it illegally accesses beyond a.
-> Undefined Behaviour.
A hint on how I spotted this:
Whenever I see [i][i], actually whenever I see [same][same],
I think "diagonal in a square". And in your code I immediatly thought "What square?", because when seeing int a[n][2]; I thought "Long narrow table." and got a conflict of shapes there.
The problem is not basically with the compiler.
You are doing
sum = sum + a[i][i];
but you have declared a 2D array of n x 2 i.e. int a[n][2]
see in some compilers it shows out of bound because you are accessing an element which is not there in the array
and in compilers it just loops in the already existing array for ex if your array has 5 elements and you are trying to access 6th element then it will go back to 1st index,
so this might be whats happening here.

Why is It make error? I want to make moving average code in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
#include <stdio.h>
#include <stdlib.h>
int main() {
int *a, *x;
int n, k;
int i; //index
int sum=0, avg=0;
a = (int*)malloc(sizeof(int)*n);
if(a==NULL)
printf("error\n");
x = (int*)malloc(sizeof(int)*n);
if(x==NULL)
printf("error\n");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
sum=0;
avg=0;
for(i=0; i<k; i++)
{
sum=sum+a[i];
avg=sum/(i+1)+0.5;
x[i]=avg;
}
for(i=k; i<n; i++)
{
sum=sum-a[i-3]+a[i];
avg=sum/3+0.5;
x[i]=avg;
}
for(i=0; i<n; i++)
{
printf("%d", x[i]);
}
free(a);
free(x);
return 0;
}
I want to make moving average code in C.
and I made the code but it has still error :(
I think I broke the basic rule in C but I don't know what it is ...
Plz help me
Let me show you what I want to make
Input example
6 3
1 3 2 10 6 8
Output
1 2 2 5 6 8
Input example 2
9 4
2 7 4 5 6 8 2 8 13
Output example
2 5 4 5 6 6 5 6 8
The primary problem is in
a = (int*)malloc(sizeof(int)*n);
where n is unitialized. It contains indeterminate value. The behavior is undefined.
Quoting C11, chapter ยง6.3.2.1,
[...] If
the lvalue designates an object of automatic storage duration that could have been
declared with the register storage class (never had its address taken), and that object
is uninitialized (not declared with an initializer and no assignment to it has been
performed prior to use), the behavior is undefined.
That said, please see this discussion on why not to cast the return value of malloc() and family in C...
That said, there are couple of more things
Take care (beware) of uninitialized variables, they are source of many problems. Initialize or assign them before they are used. Turn up your compiler warning settings, they will help you out.
int main() better be int main(void) for a hosted environment, unless you have a specialized environment/ compiler which has explicit support for int main().
On the NULL check, in case of failure, only printing the error is not sufficient, you should also discontinue the program.
printf("some_string"); is not a good practice. If you do not have to have a conversion specification required, go with puts().

Precedence of post increment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
Can anyone explain what will be the output of following code and why?
int main()
{
int i[] = {3, 5};
int* p = i;
int j = --*p++;
printf("%d\n%d\n", j,*p);
system("pause");
return 0;
}
I'm actually going to answer this question, even though it's true that "the OP simply needs to compile the code and run it", because it isn't obvious to a beginner that this is one of the cases where that gives the right answer. People get dinged all the time on this site for asking why superficially similar code (that does have undefined behavior) gives a surprising answer.
int j = --*p++;
means
int j = *p - 1;
*p = j;
p += 1;
That is, *p (the value that p points to) is decremented, the decremented value is written to j, and then p itself is incremented.
There is no undefined behavior here because the -- and ++ operators in the original form are acting on two different data objects. The expressions that have undefined behavior due to multiple use of the side-effect operators all involve modifying the same data object twice in the same expression ("without an intervening sequence point").
(If you're wondering why the -- applies to *p but the ++ applies only to p, the answer is "because that's what the grammar of the language says. Sorry, this is just one of those things you have to memorize.")

Why array self assign value (C program)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I declared a two dimensional array as row and col and I left the value empty, but when I check the value in each array position, some of the indexes contain some weird number.
You are looking at uninitilized memory. It can have whatever which value to it. You should never trust the value of a variable you haven't initialized.
Access of an uninitialized value is undefined behavior. You can solve your problem quite simply by initializing the array to all zero to begin with, e.g.
int seatNo[5][5] = {{0}};
Now any subsequent access to any of the elements of seatNo will succeed because each element has been initialized to zero. As a rule, especially when you are learning C, you will save yourself grief if you simply initialize ALL your variables.
(you will also want to turn warnings on, e.g. -Wall -Wextra, at minimum, so your compiler will warn you when a variable may be uninitialized)
#include <stdio.h>
int main (void) {
int seatNo[5][5] = {{0}};
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
printf (" seatNo[%d][%d] = %d\n", i, j, seatNo[i][j]);
return 0;
}
Example
$ ./bin/initarray
seatNo[0][0] = 0
seatNo[0][1] = 0
seatNo[0][2] = 0
seatNo[0][3] = 0
seatNo[0][4] = 0
seatNo[1][0] = 0
seatNo[1][1] = 0
<snip>

post increment about an expression [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was asked the output of following expression :-
I=10;
I++;
I++;
I++;
What will be the value of I at the end of this code. As per my knowledge, post increment in c means that first perform any other task like assignment ,printf etc and after it incteement the value of variable. Similarly in this case , first I should be 10, then I should be 10 and then it would be 11. But final answer came out to be 10 . how ?
The awnser should be 13.
int i = 10;
i++;
i++;
i++;
printf("%d", i);
test it urself
It would have been a nine-line program to demonstrate what happens to I in your question. In an expression containing I++;, I is used then incremented. In your example, since I is not used in any statement, you might have well used ++I to pre-increment it. But if a statement uses or tests I more than once, or contains a part that might not be executed, you must increment I afterwards.
#include<stdio.h>
int main() {
int I = 10;
I++;
I++;
I++;
printf ("%d\n", I); // prints 13
if (1 || I++) // I++ is not executed
printf ("%d\n", I); // prints 13
if (1 && I++) // I++ is executed
printf ("%d\n", I); // prints 14
return 0;
}
lets create an int i = 10;
i++;
is essentially the same as:
i = i + 1;
There is a slight difference though:
If you printf("%d", i++);
the printed value will be 10 since a ++ postfix will increment the value only after the value is used and i will equal 11 only on the next line, when:
printf("%d", i + 1);
will print 11 since it will be calculated before printf runs and i it self wont be changed since we didn't assign a value to it, we only used it to calculate a new value.
If you want behavior exactly the same as i = i + 1; you can use a ++ prefix like:
printf("%d", ++i);
in which case 11 will be printed and the value of i will increment by 1.
In your code you increment i using a ++ postfix 3 times without actually using i so all the code dose is increments i by one, there times. So at the end of the code i is equal to 13.
You can find more information on operators here:
http://www.tutorialspoint.com/cprogramming/c_operators.htm

Resources