values are returned but not seeing outputs - c

I'm new to programming and trying to learn C here. Below is my toy program.
#include <stdlib.h>
#include <stdio.h>
int cmp(int a, int b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
int main()
{
cmp(10, 20);
printf("testing...");
return 0;
}
My question is, in the main function, cmp() function is called, and the value 10 and 20 is passed into cmp() function.
In this case, b is larger than a, so it goes to the else branch. b should be returned, which is 20 in this case. Why am I not seeing any outputs on the terminal?

Your function will return an integer value; however, in your "main" function you call your "cmp" function but don't do anything with it. The "printf" function is only instructed to print out "testing..." currently. Here is one possible suggestion for checking the output of your function in the "main" function.
int main()
{
printf("Testing the value of cmp(10, 10) is %d\n", cmp(10, 20));
return 0;
}
Hope that helps.
Regards.

Related

C-How to increase in recursion?An example of recursively judging prime numbers

I'm a programming rookie who has not yet started. I just learned recursion and there are some problems with the use of recursion. There is a homework is judge prime numbers :using int prime(int x); and return boolean value.
Initially I found that because the variable is initialized and assigned inside the function,the program can't achieve self-increment. Because every time it enters a new level of recursion, the variable will be reassigned. Even if you write a variable auto-increment statement, it will only auto-increase the variables stored in the current recursive stack. Once the variable enters a new recursive level, the variable is only initialized according to the definition and cannot be continuously auto-incremented.
The solution to the failure is as follows:
#include <math.h>
#define false 0
#define true 1
int prime(int x){
double high=sqrt(x);
int low=2;
if((x%low==0 && x!=2) || low>high){
return false;
}
else if(x<2){
return false;
}
else{
return true;
}
low++;
return prime(x);
}
When asking questions, I found a successful solution:
#include <math.h>
#define false 0
#define true 1
int prime(int x){
double high=mysqrt(x);
static int low=2;
if((x%low==0 && x!=2)||low>high){
return false;
}
else if(x<2){
return false;
}
else{
return true;
}
low++;
return prime(x);
}
But I can't understand why using static to modify the variable can make the variable correctly increment when entering a new layer of recursion instead of executing the previous int low=2;
Ask the master to solve the confusion for me, what happened to the two in the memory space?
In addition, there seems to be another solution, which seems to be to set a flag variable, but I did not understand it. Can someone provide other solutions?
In a nutshell, ordinary variables (int low;) get created for each function call independently, while static (static int low = 2;) are created once and shared between all the functions.
However, static is not the best approach to use in such cases, because different function calls may need to have different values of high/low.
Instead, you may add explicit parameters to the function, something like this (the algorithm is wrong, but it's the general principle):
int prime(int x) { return prime_impl(x, 2, sqrt(x)); }
int prime_impl(int x, int low, double high) {
if(x<2) {
return false;
}
else if((x%low==0 && x!=2)||low>high) {
return true;
}
else {
return prime_impl(x, low+1, high);
}
}

Is it necessary to put return in a void recursion?

Feel free to make this post as a duplicate if the question asked already, I haven't found a post same as this
As far as I know that there's no need to return in a void function, e.g:
void ex () {printf ("Hi\n");}
But, is it fine if there's no return in a void recursion? What I'm thinking is, the program will keep calling func (num-1) until it reaches 0 and it returns so it doesn't print 0 to the output, and I need return at the end of the function so after the recursion call is done, you go back to the previous func () immediate caller.
Here's the code,
#include <stdio.h>
void func (int num)
{
if (!num) return;
func (num-1);
printf ("%d\n", num);
return; //Is it necessary to put return here?
}
int main ()
{
func (10);
return 0;
}
Output,
1
2
3
4
5
6
7
8
9
10
Without the last return, it works just fine too, or am I missing something?
A function with return type void doesn't need an explicit return. Simply reaching the end of the function will properly return.
It is no different for void functions that are also recursive. The first return in your function is required because you want it to return before reaching the end of the function, but the second isn't required.
A function returning void doesn't have to explicitly return. A program has 1 entry point, but might have multiple exit points. Consider the following example:
void print(int var)
{
if (var)
return; // first exit point
/*
* do stuff
*/
// second exit point
}
It has 2 exit points. Second one is without a return;.
try this :
#include <stdio.h>
void func (int num)
{
if (!num){
printf("0\n");//print 0 before you stop
return;
}
func (num-1);
printf ("%d\n", num);
}
int main ()
{
func (10);
return 0;
}

How to return to main and not the function calling it?

I have a function() which calls anotherFunction().
Inside anotherFunction(), there is an if statement which, when satisfied returns back to main() and not to function(). How do you do this?
You can't do like that in "standard" C. You can achieve it with setjmp and longjmp but it's strongly discouraged.
Why don't just return a value from anotherFuntion() and return based on that value? Something like this
int anotherFunction()
{
// ...
if (some_condition)
return 1; // return to main
else
return 0; // continue executing function()
}
void function()
{
// ...
int r = anotherFuntion();
if (r)
return;
// ...
}
You can return _Bool or return through a pointer if the function has already been used to return something else
You can't easily do that in C. Your best bet is to return a status code from anotherFunction() and deal with that appropriately in function().
(In C++ you can effectively achieve what you want using exceptions).
Most languages have exceptions which enable this sort of flow control. C doesn't, but it does have the setjmp/longjmp library functions which do this.
You can bypass the normal return sequence in C with the setjmp and longjmp functions.
They have an example at Wikipedia:
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n"); // prints
longjmp(buf,1); // jumps back to where setjmp was called - making setjmp now return 1
}
void first(void) {
second();
printf("first\n"); // does not print
}
int main() {
if ( ! setjmp(buf) ) {
first(); // when executed, setjmp returns 0
} else { // when longjmp jumps back, setjmp returns 1
printf("main\n"); // prints
}
return 0;
}

Pointer to a function via string

I have an issue with a customer. He's asking me to set up a DB table with key/values where the values are names of C functions.
He wants me to build a generic executable that will take the records of that table and call the functions stored into a C library. He wants to be able to insert or update new pairs of key/values and without modifying the executable, be able to change the function called.
As an example, I wil l post now something very similar:
int sum(int a, int b)
{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}
int (*funcion) (int,int);
{
...
funcion = (void*)"sum";
x = funcion(4,3);
funcion = (void*)"sub";
x = funcion(4,3);
}
Is this going to work?
Thanks!
You need a "lookup table".
The problem is that you need to define all functions which could be called before compilation. In order to add new functions you need to change the code. But if thats ok for you this should do the job.
#include <stdio.h>
#include <string.h>
typedef enum
{
_printf,
_scanf,
} functions;
void *get_function_ptr(int func)
{
switch (func)
{
case _printf: return &printf;
case _scanf: return &scanf;
default: return NULL;
}
}
int main(int argc, char **argv)
{
if (strcmp(argv[1], "printf") == 0)
{
void (*ptr)(char *, char *) = get_function_ptr(_printf);
(*ptr)("%s", "hi there");
}
}
Another way would, as in the comment above said, a dynamic linked library, but then you are OS dependend.

Recursive bisection method program stopped working

I have a problem with bisection method (recursive implementation) that doesn't work. The program just crashes after entering a&b values ...
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define e 0.0001
#define dbg 1
using namespace std;
double f(double x){
return x*x*x-x-2;
}
double bisection(double a,double b){
double x1;
x1=(b+a)/2;
if(x1>e){
if(f(b)*f(x1)<0)
{
a=x1;
}
else
if(f(a)*f(x1)<0)
b=x1;
bisection(a,b);
}
return x1;
}
int main () {
int a,b;
double root;
printf("a=");
scanf("%d",&a);
printf("b=");
scanf("%d",&b);
if(f(a)*f(b)<0){
root=bisection(a,b);
printf("root %g",root);
}
system("pause");
return 0;
}
I have tried to display some debugging messages, but I couldn't figure it out.
As #Gene pointed out, you never use the result of the recursive call. Further, what you DO return is just the midpoint between a&b, which you don't need recursion to find. (Related?)
Note that, if the 2 ifs used to change either a or b for the recursive call both fail, then you make a recursive call w/ unchanged values of a & b ==> infinite recursion, a sure way to get a segfault.

Resources