Defining/using outside variables inside functions? (C/C++)

Started by
3 comments, last by Lollyn00b 17 years, 4 months ago
Hello, I've been trying my hand at making a simple game engine with on OpenGL and SDL, written in C++ (although I rarely use any C++-specific things, such as classes or templates). It's been working out fine, but I was wondering if I could somehow define a variable in one function, then use it in another function, without having to define that variable outside of the function. For example, could I have an "InputInit()" function, that created an array of booleans to be used inside another "KeyCheck()" function? Right now, I've got it set up to where the array has to be defined outside of both functions, then used as a parameter in both. This is really something I'd rather happen "behind the scenes", for simplicity of use. So, is there any way I can do this? I'll explain again, if this is a bit confusing; I'm just a bit tired right now (11:41 P.M.).
Advertisement
Quote:Original post by Lollyn00b
written in C++ (although I rarely use any C++-specific things, such as classes or templates).


Then why are you using C++?

Or, why don't you take the time to learn the language (the tool) that you're trying to do work with?


Quote:Original post by RDragon1
Quote:Original post by Lollyn00b
written in C++ (although I rarely use any C++-specific things, such as classes or templates).


Then why are you using C++?

Or, why don't you take the time to learn the language (the tool) that you're trying to do work with?
I didn't say I'd never be using C++'s features; I'm actually quite interested in Object-Oriented programming. As for learning the language, that's why I was asking in this forum. I've google'd around a bit, but I haven't found anything that relates to my problem. Sorry if my question was too base for "For Beginners".

Since you are using C++, I would wrap them in an Input class, and just use member variables. If, for some reason you really dont want to do that (then you shouldn't be using C++, but I digress...), then you could just pass pointers around as function params, you'll just need to new[] the array so it doesnt fall out of scope, and delete[] it when you are done.
Edit: Or, better yet, use a std::vector.
Quote:Original post by Driv3MeFar
Since you are using C++, I would wrap them in an Input class, and just use member variables. If, for some reason you really dont want to do that (then you shouldn't be using C++, but I digress...), then you could just pass pointers around as function params, you'll just need to new[] the array so it doesnt fall out of scope, and delete[] it when you are done.

D'oh, I never thought to use member functions. Thanks, that was a lot simpler than I expected my problem to be!

This topic is closed to new replies.

Advertisement