This edit of your code shows how to use your function 2 with two number you enter.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun_one(int a,int b);
void fun_two(int a,int b);
int main(int, char **);
int main(int argc, char ** argv)
{
int a,b;
a= atoi(argv[1]);
b=atoi(argv[2]);
printf("Result=");fun_two(a,b); // similar to what you want from comments
//using both functions
printf("a+b=");fun_one(a,b);
printf("a*b=");fun_two(a,b);
return 0;
}
void fun_one(int a,int b){
printf("%d\n",a+b);
return;
}
void fun_two(int a,int b){
printf("%d\n",a*b);
return;
}
I have revised your code so that if you compile it with
gcc -o exec exec.c
You will be able to run it with
./exec 4 3
to get the required output - note that I expect compilation with cc
will give exactly the same output, but I can't test it.
What I have done is changed the definition of main
so that it can accept input from when you call it. The extra bits are put into strings.
The function atoi
converts ascii string to an integer number so that the numbers you put on the command line can be handled as numbers and not as strings.
Please note that this code is rather fragile and may seg. fault. if you don't put in two numbers after you call the program the result will be unpredictable. You could make it more reliable by checking the value of argc - the number of things typed on the line when you entered the command and by checking that atoi worked, but that would make the code longer and I think it is more important to see a way of doing what you want to achieve at the moment.
A more versatile code is below, which allows you to choose which function you want to run in the code....
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun_one(int a,int b);
void fun_two(int a,int b);
int main(int, char **);
int main(int argc, char ** argv)
{
int a,b;
a= atoi(argv[2]);
b=atoi(argv[3]);
if (!strcmp("fun_one",argv[1]))
{
printf("Result=");fun_one(a,b);
}
else if (!strcmp("fun_two",argv[1]))
{
printf("Result=");fun_two(a,b);
}
else printf("Didn't understand function you requested. \n\n");
return 0;
}
void fun_one(int a,int b){
printf("%d\n",a+b);
return;
}
void fun_two(int a,int b){
printf("%d\n",a*b);
return;
}
The function now gives the following output for the following input
./exec fun_three 3 4
Didn't understand function you requested.
./exec fun_one 3 4
Result=7
./exec fun_two 3 4
Result=12
so now with the code above you enter three things after the command - the function you want, then the two numbers - if the function is not recognised there is an error message.
The function strcmp
compares two strings and returns zero if they are identical. zero is equal to false in logic so the !
symbol is used as a not, which converts zero to one and numbers not equal to zero to zero. The effect is that if the two string are identical the logical test will be true.