How to pass value from one function to another in C? - c

Here I have two functions and I call Both of them in my MAIN function. The first function gives me a value of "wage" and I want to use the value of "wage" in my 2nd function. But this doesn't work. Also, I will be using my variable in another function later in my code. Is there any way to call my values efficiently?
Here is the main function call:
#include <stdio.h>
#include <string.h>
int main()
{
categoryA();
workingInfo();
}
1st function that has value of "wage" :
void categoryA()
{
printf("\n\nCategory A: Administrative Worker[1]\n\t Data Entry Operator[2]\n\t Data Entry Clerk[3]\n\t Betting Clerk[4]\n");
int position;
float wage;
float overWage;
char positionName[100];
printf("Choose Your Job Title : ");
scanf("%d",&position);
if(position == 1)
{
wage = 12.5;
overWage= wage*1.15;
strcpy(positionName, "Administrative Worker");
}
else if (position == 2)
{
wage = 13;
overWage= wage*1.15;
strcpy(positionName,"Data Entry Operator");
}
else if (position == 3)
{
wage = 13.2;
overWage= wage*1.15;
strcpy(positionName, "Data Entry Clerk");
}
else
{
wage = 13.5;
overWage= wage*1.15;
strcpy(positionName,"Betting Clerk");
}
printf("wage in the category function : %.2f\n",wage);
}
2nd function where I want to use "wage" :
void workingInfo(float wage)
{
printf("wage in the working info %.2f\n",wage);
}

Change the function so that it returns a float, i.e.
float categoryA()
{
... your current code ...
return wage; // Return the value of wage
}
and use it like:
int main()
{
float f = categoryA(); // Save the returned value (i.e. wage) in
// a variable with the name f
workingInfo(f); // Use f
....
someOtherFunc(f); // Use f again
}
or the more compact version:
int main()
{
workingInfo(categoryA()); // The returned value isn't saved in
// a variable but passed directly to
// the workingInfo function
}

Once categoryA() has returned, its wage variable is gone, as well as out of scope. There's no way it can be accessed.
Rather, I suggest you return wage; at the end of categoryA(), then pass the result in to workingInfo().
You'll need to change the signature of categoryA():
float categoryA()
And change the call to something like:
float wage = categoryA();
workingInfo(wage);
... or...
workingInfo(categoryA());

The simplest way you can do it by making wage as global variable, then also you will be able to use it with in multiple functions too and you can also use it as pointer too if you are comfortable with pointers.

Related

Why is my variable not updating when I use a switch statement?

I am a student, and I am trying to make an adventure text game, without using arrays.
This code is a function, called by main (within another switch case statement). The problem is, the day doesn't update. It only updates when the code is included inline in main.
int getArea (int nArea) //area and day
{
int nShisha, nBall, nLolipop, nPepsi ;
int nUser; //test variables
int nPrice; // testing variable for price
int naUser ;
int nDay;
nDay = 2;
printf("Choose your Area\n");
printf("1. Riyadh\n2. Jeddah\n3. Albaik\n4. Tazaj\n");
printf("5. Go back\n");
scanf("%d", &nArea);
//nArea
do{ //This is for the place
switch (nArea)
{
case 1 :
printf("Riyadh\n");
printf("Day %d of 15\n", nDay);
nDay ++;
if (nDay == 16) {
return 0;
}
getPrice (&nShisha , &nBall, &nLolipop, &nPepsi ) ;// add charge soon
break;
case 2 :
printf("Jeddah\n");
printf("Day %d of 15\n", nDay);
nDay ++;
if (nDay == 16) {
return 0;
}
getPrice (&nShisha , &nBall, &nLolipop, &nPepsi ); // add charge soon
break;
case 3:
printf("AlBaik\n");// add charge soon
printf("Day %d of 15\n", nDay);
nDay ++;
if (nDay == 16) {
return 0;
}
getPrice (&nShisha , &nBall, &nLolipop, &nPepsi );;
break;
case 4:
printf("Tazaj\n");// add charge soon
printf("Day %d of 15\n", nDay);
nDay ++;
if (nDay == 16) {
return 0;
}
getPrice (&nShisha , &nBall, &nLolipop, &nPepsi );;
break;
default : printf("You have entered invalid!");
break;
}
// printf("do you want to go to another place?\n"); //test code change later into better alternative
scanf("%d", &nArea);
}while (nArea!=0); //for area while
}
Can you guys please explain why is it not updating?
Per your clarification, you are talking about variable nDay. In the code presented in the question, this variable is local to function getArea(). I am confident that it is successfully updated in the function, but that will have no effect on any like-named variable in main() or elsewhere. Those are different variables with the same name. Since you describe factoring this code out of main into its own function, I am fairly confident that this is the nature of the problem.
If you want the function to modify a variable that is local to the caller, then the caller must pass a pointer to that variable, and the function must update the caller's variable indirectly, via the pointer. For example, you might declare getArea() like this, instead:
int getArea(int area, int *nDay) {
// ...
You would then also need to get rid of the other declaration of nDay inside getArea():
int nDay;
, and all other appearances of nDay inside the function body would need to be replaced with (*nDay).*
For its part, the caller would need to pass the appropriate pointer, something like:
int main(void) {
int area, rval, nDay;
// ...
rval = getArea(area, &nDay);
// ...
}
* Technically, the parentheses are needed only in some cases, but they are harmless in the rest.
The value of a variable in a user-defined function won't be updated in main() function as long as you are not returning it to to the main() function or the variable is a pointer that had been passed from the main function.
In your code, even though the variable nDay has been updated in the function getArea, the variable won't be updated in main() function if you don't return it. you can use
int getArea (int nArea)
{
...
...
return nDay; // Only this value will be passed to the main() function. nothing else updated here will be passed.
}
int main()
{
int x,y,z, nArea, nDay;//some variable that you declared. Assuming nDay is one of them
...
...
nDay=getArea(nArea); //value returned from the function(which is "nDay" from getArea()) will be assigned to nDay
...
}
Also, I don't see any reason for passing nArea to getArea() as you are overwriting/taking new input(value) of nArea inside the function.
Note the nDay from main() and nDay from getArea() are actually different variable even though they have the same name.

How can I use the result from a function as a parameter to another function in C?

In a function that returns void and has no parameters I want to use two other functions (unfortunately I cannot modify that). The first of these functions calculates the result of an int and I want to pass that result as a parameter to the second function. How could I achieve that? thank you.
void descriptionEdit(void)
{
while(1)
{
int fieldno;
if (!pluFields())
{
break;
}
start_editor(setf, esize);
do
{
//code
} while(fieldno>=0);
saveEditor();
}
}
bool pluFields(void)
{
**edplu** = search_productcode();
if (edplu == 0)
{
return true;
}
}
void saveEditor()
{
if (save_plu(**edplu**, &plu))
{
CloseProductIniFile();
cls();
writeat(30, 6, INV2X3, "Save Confirmed");
}
}
So, I want somehow to use the edplu from pluFields function as a parameter to saveEditor function, I thought to make edplu global variable but I think this is a bad practice
You algorithm is very non-intuitive. However, to get a value of a function and pass to another function do this:
int functionName(int param1) {
// calculate values
return variable_here
}
int value = functionName(param1)
then value will go onto the parameter of your next function, like that
void function2(int value) ...
function2(value)
Let me know if I helped.

How to create derived structure properties in C

In Python, its possible to create a derived property from a class using the #property decorator for example
class State():
def __init__(self, fav_num_monday, fav_num_not_monday, is_monday):
self.fav_num_monday = fav_num_monday
self.fav_num_not_monday = fav_num_not_monday
self.is_monday = is_monday
#property
def fav_num(self):
return self.is_monday * self.fav_num_monday + \
(1 - self.is_monday) * self.fav_num_not_monday
state = State(12, 5, 0)
print("Current favourite number: %d" % state.fav_num)
My question is then what is the best way to achieve this in C (where speed is of the utmost importance). I've have added below some ways I have tried but am not sure if they could have repercussions in a larger codebase. They are as follows:
Simply writing out the whole expression each time.
Pros: No unexpected repercussions, no code/speed penalty.
Cons: Ugly code, takes a long time to write.
Using a get function.
Pros: Code easier to read.
Cons: Inefficient code (slower than 1).
Defining a macro.
Pros: No code/speed penalty. Code quick to write.
Cons: Potential repercussions later, code not so easy to follow.
The example program is below
#include <stdio.h>
#include <string.h>
#define state_fav_num state.is_monday * state.fav_num_monday + (1 - state.is_monday) * state.fav_num_not_monday
struct State {
int fav_num_monday;
int fav_num_not_monday;
int is_monday;
};
int get_state(struct State *state, char *property) {
// Returns value of the property in state.
// Allows us to create derived properties also.
if (!strncmp(property, "fav_num_monday", 14)) {
return state->fav_num_monday;
} else if (!strncmp(property, "fav_num_not_monday", 18)) {
return state->fav_num_not_monday;
} else if (!strncmp(property, "is_monday", 9)) {
return state->is_monday;
} else if (!strncmp(property, "fav_num", 7)) {
return state->is_monday * state->fav_num_monday +
(1 - state->is_monday) * state->fav_num_not_monday;
}
}
int main() {
// Set the state.
struct State state;
state.fav_num_monday = 12;
state.fav_num_not_monday = 5;
state.is_monday = 1;
// Print favourite number in different ways.
printf("\n1) Current favourite number is %d.",
state.is_monday * state.fav_num_monday +
(1 - state.is_monday) * state.fav_num_not_monday);
printf("\n2) Current favourite number is %d.",
get_state(&state, "fav_num"));
printf("\n3) Current favourite number is %d.",
state_fav_num);
printf("\n");
return 0;
}
You can get the best of both worlds (function and macro) for readability and performance, with a static inline function.
You usually wouldn't use that, but if you know the compiler is going to optimize its code away, then it's OK to use it. The usual rule I use is 3 or less lines of code, and the function should require extra performance.
That said, your get_state doesn't meet the (my) requirements for a static inline function, but if you only want a function to get only the fav_num, it would make sense:
struct State {
int fav_num_monday;
int fav_num_not_monday;
bool is_monday;
};
static inline int get_fav_num(const struct State *state)
{
if (state->is_monday)
return state->fav_num_monday;
else
return state->fav_num_not_monday;
}
int main(void)
{
struct State state;
int fav_num;
state = (struct State){
.fav_num_monday = 12;
.fav_num_not_monday = 5;
.is_monday = 1;
};
// Print favourite number in different ways.
printf("\n");
if (state.is_monday)
fav_num = state->fav_num_monday;
else
fav_num = state->fav_num_not_monday;
printf("1) Current favourite number is %d.\n", fav_num);
fav_num = get_fav_num(&state);
printf("4) Current favourite number is %d.\n", fav_num);
return 0;
}
Disclaimer: This code needs C99 or later.
Although here the code is all together, the struct State {...}; and the static inline function would usually go in a header .h file.
Also, I would improve your get_state function in this way:
enum Properties {
FAV_NUM_MONDAY,
FAV_NUM_NOT_MONDAY,
IS_MONDAY,
FAV_NUM
};
int get_state(const struct State *state, int property)
{
switch (property) {
case FAV_NUM_MONDAY:
return state->fav_num_monday;
case FAV_NUM_NOT_MONDAY:
return state->fav_num_not_monday;
case IS_MONDAY:
return state->is_monday;
case FAV_NUM:
return get_fav_num(state);
default:
return -1; /* Error */
}
}
This function would be a usual extern function and would go in a .c file, although the enum Properties should go in a header file so that it can be used by the user of the function.
Edit: Add high performance version using array
state.h
#include <stdint.h>
enum State_Properties {
FAV_NUM_MONDAY,
FAV_NUM_NOT_MONDAY,
IS_MONDAY,
STATE_PROPERTIES
};
static inline
uint_fast8_t get_fav_num(const uint_fast8_t *restrict (state[STATE_PROPERTIES]))
{
if ((*state)[IS_MONDAY])
return (*state)[FAV_NUM_MONDAY];
else
return (*state)[FAV_NUM_NOT_MONDAY];
}
main.c
#include <inttypes.h>
#include "state.h"
int main(void)
{
uint_fast8_t state[STATE_PROPERTIES];
uint_fast8_t fav_num;
uint_fast8_t fav_num_monday;
state = (uint_fast8_t [STATE_PROPERTIES]){
[FAV_NUM_MONDAY] = 12;
[FAV_NUM_NOT_MONDAY] = 5;
[IS_MONDAY] = true;
};
// Print favourite number in different ways.
fav_num = get_fav_num(&state);
printf("5) Current favourite number is %"PRIuFAST8".\n", fav_num);
// Example of how to retrieve any property:
fav_num_monday = state[FAV_NUM_MONDAY];
}
Of course you can change the type to anyone you want. I used uint_fast8_t, because your data can fit in there, and it is the fastest type on any system.

Assignment to write a program that gives the user a choice between two options - C

I have an assignment due and I am drawing a blank on what exactly to do... I'm sure it is simple but I havent quite gotten the hang of things yet. The assignment is -
Write a program that gives the user 2 menu options: either call a function that will print a greeting and your name 4 times or call a function that will count down from 10 to 0 and then print "Blastoff!". Both functions should use for loops to print the appropriate output.
I have the prompt and the functions done so far... but I am unsure of how to display one or the other depending on the choice the user makes. Thank you for your help.
#include <stdio.h>
int main (void){
// declare counter variable
int i;
// prompt the user to make a choice
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n");
printf("\n");
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
You should read the input from user's keyboard:
int c;
c = getchar();
if (c == '1')
{
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
if (c == '2')
{
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
}
printf("Blastoff!");
you should use Switch case.
switch(choice) {
case 1: //first for loop
break;
case 2: //second for loop
break;
}
Looks like you are missing a couple of points here. Firstly, you have not yet written any functions. Try looking here to gain some insight on that front.
Secondly, to make a choice based on user input you need to actually get that input somehow. You'll probably want to use scanf.
Lastly, once you have the user's input (say, in a variable declared as int input;) you can use if to control the flow of your program based on that variable like this:
if(input == 1){
greet();
}
else {
countDown();
}
Cheers! If you have any further questions feel free to comment below.
First of all you haven't actually declared you functions. Functions in C should be declared like the main function is. For more info in this see here.
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
To get the user's input the most common way is by keyboard. scanf accomplishes that in C. Details on scanf here
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
}
Lastly to decide what to do based on the user input you can use either an if then else statement or a switch. I will provide a solution with an if statement and you can figure the one with the switch on your own. Your final code should look like this.
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
if(choice == 1){
greeting();
}else{
countdown();
}
}
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
Bear in mind that this code has a lot of flaws (error checking mainly) but I guess your assigment is not about that.
First of all you need to include libraries with function you will need. You do this by
#include <someLibrary.h>
at the beggining of you document. Libraries mostly have .h extension. Always look for them if you try to do something. You consider them to have best performance and functionality as possible (not always true).
What is next you declare your functions. Function has name, arguments which are going into it, body in which they do something and return value (can be float, int, char etc). If function doesnt return anything, they return void (dont have return at the end). You declare functions before main() with only types of arguments. Whole body is after main (it is better looking).
If you declared function with arguments, you have to provide these arguments to function in () brackets. Even if no arguments are needed, you use them like getch() in example below. Note that function become what it return. If you declared some new variables in function they will be visible only in function. On the other hand function will not see any variable from other function (main too). If you want so, declare global variables (not recommended).
#include <stdio.h>
#include <conio.h> //libraries
void function1(int);
float function2(float); //declaration of functions
int main()
{
char decision;
printf("press 'a' to run function1, press 'b' to run function2\n");
decision=getch(); //first see getch()? look in google for functionality and library !
int someInt=10;
float someFloat=11;
if(decision== 'a')
{
function1(someInt);
}
else if(decision == 'b')
{
printf("%f", funcion2(someFloat)); //example that function become what they return
}
else
{
printf("No decision has been made");
}
getch(); //program will wait for any key press
return 0;
}
void function1(int param1)
{
//print your stuff // this function return void, so doesnt have return; statement
}
float function2(float param1)
{
return 2*param1; //this function have to return some float
}

map function pointers to specific numbers at runtime

I have a problem that i can even start to work on because i don't get it how can be done.
So we have a code
int test_handler() {
printf("Test handler called\n");
return 1;
}
// Test your implementation here
int main()
{
register_irq_handler(30, &test_handler);
do_interrupt(29); // no handler registered at this position, should return zero
do_interrupt(30); // calls handler at position 30, expected output: Test handler called
return 0;
}
I need to make those functions register_irq_handler, do_interrupt(29).
But i have no clue how to start, i am looking for a little help to send me on the right direction.
How i store 30 to point to this function when we don't have a global variable to store that "connection" or i am missing something.
You can't do it without a global variable (why would having a global variable be a problem?).
You probably need something like this:
// array of 30 function pointers (all automatically initialized to NULL upon startup)
static int(*functionpointers[30])();
void register_irq_handler(int no, int(*fp)())
{
functionpointers[no] = fp;
}
int do_interrupt(int no)
{
if (functionpointers[no] != NULL)
{
// is registered (!= NULL) call it
return (*functionpointer[no])();
}
else
{
// not registered, just return 0
return 0;
}
}
Disclaimer
This is non tested non error checking code just to give you an idea.

Resources