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 6 years ago.
Improve this question
In the following C code, f calls g, and g calls h. Notice the goto in h, however: it will jump back to f if a satisfies a certain condition.
void h(int a)
{
if (a > 10)
goto out;
}
void g(int a, int b)
{
h(a);
}
void f(int a, int b)
{
g(a, b);
return;
out:
printf("b: %d\n", b);
}
My question is: how will the stack be if the goto is triggered? Will g and h be unstacked? And will f still print the right value of b? (or will it print it right only in some cases when I am lucky?)
(Please, I don't want to discuss if this is a good practice, or if this should be used at all. Also, consider that the actual code is complicated enough so that the compiler won't be smart enough to, e.g., optimize g out)
[I can give details on why I am doing this, if it matters -- I don't think it does]
This will result in undefined behavior in standard C.
From 6.8.6.1/1 of the C Language Standard:
The identifier in a goto statement shall name a label located
somewhere in the enclosing function. A goto statement shall not jump
from outside the scope of an identifier having a variably modified
type to inside the scope of that identifier.
The question is void, because it simply cannot be done like this: you only can goto within a function, not between functions.
For jumping between functions, you can use setjmp/longjmp.
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function.
Labels are local to a single function, you cannot jump between different functions.
NOTE − In my opinion the use of goto statement is highly discouraged.
ref: http://www.tutorialspoint.com/cprogramming/c_goto_statement.htm
You cannot do this since labels are local to each particular function. However, the nearest standard equivalent is the setjmp() and longjmp() pair of functions. That should work. :)
Related
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 6 months ago.
Improve this question
I wrote the following C program to find the output for a+++b
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a+++b);
}
And I'm getting the output as 7 which is correct according to lexical analysis.
Apart from that I wrote a separate program to find the output for a++ +b
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a++ + b);
}
For the above program again I'm getting output as 7 (which is again correct according to lexical analysis)
But when I wrote a program to print the outputs for both a+++b and a++ +b I'm getting different outputs
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a+++b);
printf("\n%d",a++ + b);
}
The output is 7 for a+++b (which is correct) and 8 for a++ +b (which is wrong).
Can anyone point out the error in the third program?
a++ is post-fix increment. It evaluates to a and increments the variable a by 1 before the enclosing printf() is called in this case(*).
So after the first printf() the value of a is 6.
So what do you now expect from the second printf?
Operators like post-fix ++ are expressions (have a value) and instructions (have an effect). They cause endless confusion bugs and undefined behaviour to novices and bite the most seasoned programmers on the ass from time to time.
(*) These operators are useful and have their place but exactly when these operators take effect is complex sometimes counter intuitive and I recommend you don't use them in complex expressions to begin with or even ever.
They're a bit of a throw back to when compilers didn't optimise code for you and the programmer had to help!
The issue here isn't the space in the second statement, it's the fact you have two of them. After the first statement (to be exact, after a++ is called), the value of a is incremented and is now 6. So a++ + b will clearly return 8. If you omit the first printf call and just call the second one, you'll get 7 as you expect.
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 3 years ago.
Improve this question
I don't get what I should put in the place of: "α" and "β" in order to print all the 3 digit numbers which are different from 0 and from one another.
It is required to replace those 2 variables, with some code
We are entering G(0)!!!
It's from an exam paper, I really don't get it, please help.
void G(int k)
{int i;
for(i=1;i<=α;i++)
{ p[k]=i;
if(β)G(k+1);
else
printf("%d%d%d\n",p[0],p[1],p[2]);
}
}
For any of this to make sense, it must be that p is declared as a global int array of dimension at least 3. I assume for the purposes of this answer that it is in fact so declared.
Note that the function sets p[k] = i, but it later reads back only p[0], p[1], and p[2]. This should give you a pretty good idea about what makes sense for expression β, which controls whether to recurse (increasing k) or print.
Note also that the function sets p[k] = i, and that when it reads back those p[k] for various k, it wants to get values ranging from 1 to 9 (no more and no less). This should give you a pretty good idea of what expression makes sense for α, the inclusive upper bound on i.
Having figured those out, it remains to satisfy yourself that the natural substitutions for those expressions indeed produce a resulting function that behaves as required when initially called as G(0). I suspect that you will find that easier than you did discerning the needed expressions.
(Details are left as an exercise.)
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 4 years ago.
Improve this question
so I've written some codes to add two numbers in C, but I can't figure out how to add three instead without spilling the results into another variable or clobbering the caller's version of the variables?
int add(a,b,c)
int a, b, c;
{ int tempr;
for(;b--;++a); // danger
/*tempr = c+a;*/
tempr = a+c;
return (tempr);
}
Here's how, if you must use a function for some reason.
int add(int a,int b,int c) {
return a+b+c;
}
When you define a function in C, you have to define the type of the parameters as well.
Please note the following:
It is an error to define a variable in a function that has the same name as a function parameter
Although not an error, there's no need for parentheses when calling return (tempr);.
return tempr; is perfectly fine
if you use a for loop, ending it with ; immediately after the for statement will result in the following statement not being a part of the loop. This might not be what you had in mind.
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
int main(void) {
long fall, n, k, p, i, j, r;
long long x, y, a[110][110];
for(a[0][0]=scanf("%ld",&fall);fall--;printf("%lld\n",y)) {
for(i=!!scanf("%ld%ld%ld",&n,&k,&p);i<=k+1;i++)
for(j=0;++j<=i;a[i][j]=(a[i-1][j-1]+j*a[i-1][j])%p)
;
for(y=!(j=1);j<=k+1;y=(y+a[k+1][j++]*x)%p)
for(x=!((r=n%j)*!(i=-1));++i<j;x=x*(n-i)/((i==r)?j:1)%p)
;
}
return 0;
}
How does for loop work here? It doesn't follow the syntax as I see.
for loops have the following pattern:
for(initial expression; conditional expr; afterthought)
I'll break down the first loop for you, you should be able to do the rest on your own.
for(a[0][0]=scanf("%ld",&fall);fall--;printf("%lld\n",y))
The initialization part of this loop is a[0][0]=scanf("%ld",&fall).
scanf is used for reading input and returns the number of input values. In this case, it will be 1 and it gets assigned to a[0][0].
fall-- is the conditional expression. In C, positive numbers are evaluated as true. So this loop will run until fall == 0.
printf("%lld\n",y) is the afterthought. It gets run after each loop iteration. In this case, it will simply print the value.
Unraveling obfuscated code can be a good learning exercise though you must obviously never use it in practice.
This code abuses the fact that the first and third conditions of the for loop does not necessarily need to have anything to do with the loop itself. At its core, the for loop simply executes an initial expression, performs the conditional check and executes the afterthought after every iteration.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Suppose we have a recursive function, f, that might fail if the input is incorrect. The error in the input can only be detected while f is running.
What is the idiomatic way in C to break out of f(), straight to the original calling function, in case of an error?
Is setjmp/longjmp the usual solution here?
Toy example:
void g() {
int arr[] = {1, 2, -3, 4};
int result = f(0, sizeof(arr)/sizeof(int) - 1, arr);
/* if f() was successful: */
printf("%d\n", );
/* if error occurred in f: do something else */
}
int f(int n, int i, int *arr) {
if (i < 0)
return n;
/*
if (arr[i] < 0) <-- "erroneous input"
break to g()
*/
return f(arr[i] + n, i-1, arr);
}
Options are:
Return a status flag from f() indicating success or failure. This causes the error to bubble up one level at a time from the depth at which the error occurs, so may not be what you want. Note that this is the only safe option if you need to unwind any allocations or release resources which f() may have claimed at each level.
Use setjmp() and longjmp() exactly as you suggest to simulate the effect of throwing an exception and jump directly to the error-handling code.
The usual way is it return a value indicating an error, mostly -1 is used.
I think longjmp is the way to go. I would not at all consider it good coding style, though.
It becomes harder to see what your code does if you start introducing jumps in it. There are also numerous problems:
code readability suffers
you can only call your function from one place, thus reuse of the code is severely limited
it's easy to introduce memory leaks when using longjmp
the resulting code is much more brittle (breaks easier, for example when introducing some piece of code above the setjmp)
Unless you have very specific performance requirements, try to avoid it and instead let an error result bubble back down to your original caller.
If the recursion will be deep, I would think longjmp makes more sense. Otherwise returning costs an extra O(N) (where N is the number of levels of recursion), and that includes thrashing the cpu cache with tons of pages of stack frames (each stack frame is likely to be a whole cache line).
Some will argue that longjmp is "bad style", and I will agree, but using deep recursion is much worse style already anyway... (And likely to have much worse effects, like blowing away your stack and crashing the program or yielding privilege compromise, not just looking ugly.)