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?)

Recommended Answers

All 10 Replies

// 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;
}

Did this compile? This is the C forum.

void alterValueTwo (int& input)

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)

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?

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....)

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

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.

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

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.

Great information!

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

commented: You're welcome :-) +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.