1.11M Members

Variables in separate functions

 
0
 

I'm coding an inventory program in C
and I need the variable "stock1" in more than two seperate functions

I'm not sure as to how they're supposed to be manipulated and read by the seperate functions
nor do I understand how to declare them

If I declare them as global variables then I'm almost certain that
they won't be manipulated by the seperate functions.

Anyway I can declare them so that I can change the values IN the separate functions?

(is it the use of a pointer?)

 
0
 
// top level

int stock1 = 0;

// first way - pass by value and get return value
stock1 = alterValueOne(stock1);

// second way - pass a pointer to the variable
alterValueTwo(&stock1);

// functions
int alterValueOne (int input)
{
  int temp = input + 7;
  return temp;
}

void alterValueTwo (int& input)
{
  *input = *input + 7;
}
 
0
 

Did this compile? This is the C forum.

void alterValueTwo (int& input)
 
0
 

Oop. Typo from sloppy copying of the example usage. Meant to be a pointer, as used inside the function itself. Read as

void alterValueTwo (int* input)
 
0
 

Thank you so much!

For the pointer should I declare the stock variables as them as global variables?
and how do i declare more than one variable into the function with pointers on them as well?

 
0
 

For the pointer should I declare the stock variables as them as global variables?

Almost certainly not. Create them in the main function, and then pass pointers to them into the functions that need to change them.

and how do i declare more than one variable into the function?

void someFunction(int* firstVariable, double* secondVariable, char* thirdVariable, etc etc....)
 
0
 

got everything now :)
thank you so much
are the other languages any easier than c?

 
0
 

are the other languages any easier than c?

Depends on which "other" languages you're thinking about, but in general, yes. C is a simple language, but it's not easy because it doesn't hold your hand. You need to think about and manage a lot of low level things to write good C.

 
0
 

I heard Java's syntax is similar to C
I'm planning to do Java and HTML hopefully..

 
0
 

I heard Java's syntax is similar to C

It's derived from C, yes. Java as a language is easier than C, in my opinion, but as soon as you throw in the gigantic standard library it gets harder.

 
1
 

Great information!

This post has been really helpful,
and I can contribute as much as you all in the future years. :)

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: