473,473 Members | 2,080 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Special Case: Creating a variable in a function?

How would you declare and assign a variable inside a function THAT HAS
THE NAME OF A PARAMETER YOU PASSED

example:
when you call createvariable("myvariable")

it will declare the variable "myvariable"
and then maybe assign it something.
myvariable = "this is a real variable"

also so you can use it later, outside of the function.

Apr 17 '07 #1
13 1990
Ju*************@yahoo.com wrote:
How would you declare and assign a variable inside a function THAT HAS
THE NAME OF A PARAMETER YOU PASSED
Please don't shout!
example:
when you call createvariable("myvariable")

it will declare the variable "myvariable"
and then maybe assign it something.
myvariable = "this is a real variable"
You can't. What problem are you trying to solve?

--
Ian Collins.
Apr 17 '07 #2
Your question is very hard to understand. Can you try to be a little
clearer in your problem? Maybe some code.

Apr 17 '07 #3
Gaijinco wrote:
Your question is very hard to understand. Can you try to be a little
clearer in your problem? Maybe some code.
Which question, please retain context on Usenet posts.

--
Ian Collins.
Apr 17 '07 #4
Ju*************@yahoo.com wrote:
How would you declare and assign a variable inside a function THAT HAS
THE NAME OF A PARAMETER YOU PASSED
Please do not use ALL CAPS. It looks like you are SHOUTING.
example:
when you call createvariable("myvariable")

it will declare the variable "myvariable"
and then maybe assign it something.
myvariable = "this is a real variable"

also so you can use it later, outside of the function.
There are no variable names when the program is running. They
exist only for the programmer's convenience while he/she is
writing the program. Once the program has been processed by
the compiler, the code and all its individually recognizable
elements have been converted to machine instructions and
addresses.

If you need to tag objects in your program with some kind of
symbolic constructs (like names, IDs, etc.), you're free to do
so using whatever constructs you feel suited for that. For
example, you can add a data member to your class and give it
the type 'std::string' and make it store what you'd interpret
as a name of the instance of the class. Perhaps you could
elaborate on what you're trying to accomplish...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 17 '07 #5
Gaijinco <ga******@gmail.comwrites:
Your question is very hard to understand.
Followups that don't quote context are very hard to understand too. What
question are you talking about?

sherm--

--
Web Hosting by West Virginians, for West Virginians: http://wv-www.net
Cocoa programming in Perl: http://camelbones.sourceforge.net
Apr 17 '07 #6
On Apr 16, 8:08 pm, Ian Collins <ian-n...@hotmail.comwrote:
Justcallmedr...@yahoo.com wrote:
How would you declare and assign a variable inside a function THAT HAS
THE NAME OF A PARAMETER YOU PASSED

Please don't shout!
Sorry :D
example:
when you call createvariable("myvariable")
it will declare the variable "myvariable"
and then maybe assign it something.
myvariable = "this is a real variable"

You can't. What problem are you trying to solve?

I'm trying to create a game engine and one of the functions i'm trying
to create involve loading a mesh and then having the materials for it
end up in an array.

void create_mesh(LPCWSTR path, char array arraynew) // just... kind of
ignore that second parameter.
{

// complicated stuff here to make arraynew work
LPD3DXBUFFER bufNew;

D3DXLoadMeshFromX (path, // load this file
D3DXMESH_SYSTEMMEM, // load the mesh into
system memory
d3ddev, // the Direct3D Device
NULL, // we aren't using adjacency
&bufNew, // put the materials here
NULL, // we aren't using effect instances
&numMaterials, // the number of materials in
this model
&meshSpaceship); // put the mesh here

// retrieve the pointer to the buffer containing the material
information
D3DXMATERIAL* tempMaterials = (D3DXMATERIAL*)bufNew-
>GetBufferPointer();
// create a new material buffer for each material in the mesh
material = new D3DMATERIAL9[numMaterials];

for(DWORD i = 0; i < numMaterials; i++) // for each material...
{
arraynew[i] = tempMaterials[i].MatD3D; // get the material
info
arraynew[i].Ambient = material[i].Diffuse; // make ambient
the same as diffuse
}

return;

so far the path parameter works. you can put any character string that
is a filename into it. ex: "mymeshfile.x"
i want to do the same sort of thing for creating an array.
*I want to be able to call the function as many times i want to
without having to also put a declaration for each array at the top.
*basically i want a stand-alone function.

Apr 17 '07 #7
On Apr 16, 9:23 pm, Justcallmedr...@yahoo.com wrote:
>
You can't. What problem are you trying to solve?

I'm trying to create a game engine
This may be off-topic, but is this for educational purposes? There
are some good, stable, open-source engines out there already
(Irrlicht, Ogre3d, Blitz3D, CrystalSpace, etc.).

Apr 17 '07 #8
On Apr 16, 9:40 pm, dave_mikes...@fastmail.fm wrote:
On Apr 16, 9:23 pm, Justcallmedr...@yahoo.com wrote:
You can't. What problem are you trying to solve?
I'm trying to create a game engine

This may be off-topic, but is this for educational purposes? There
are some good, stable, open-source engines out there already
(Irrlicht, Ogre3d, Blitz3D, CrystalSpace, etc.).
yep.

Apr 17 '07 #9
On Apr 16, 9:23 pm, Justcallmedr...@yahoo.com wrote:
On Apr 16, 8:08 pm, Ian Collins <ian-n...@hotmail.comwrote:
Justcallmedr...@yahoo.com wrote:
How would you declare and assign a variable inside a function THAT HAS
THE NAME OF A PARAMETER YOU PASSED
Please don't shout!

Sorry :D
example:
when you call createvariable("myvariable")
it will declare the variable "myvariable"
and then maybe assign it something.
myvariable = "this is a real variable"
You can't. What problem are you trying to solve?

I'm trying to create a game engine and one of the functions i'm trying
to create involve loading a mesh and then having the materials for it
end up in an array.

void create_mesh(LPCWSTR path, char array arraynew) // just... kind of
ignore that second parameter.
{

// complicated stuff here to make arraynew work
LPD3DXBUFFER bufNew;

D3DXLoadMeshFromX (path, // load this file
D3DXMESH_SYSTEMMEM, // load the mesh into
system memory
d3ddev, // the Direct3D Device
NULL, // we aren't using adjacency
&bufNew, // put the materials here
NULL, // we aren't using effect instances
&numMaterials, // the number of materials in
this model
&meshSpaceship); // put the mesh here

// retrieve the pointer to the buffer containing the material
information
D3DXMATERIAL* tempMaterials = (D3DXMATERIAL*)bufNew-
GetBufferPointer();

// create a new material buffer for each material in the mesh
material = new D3DMATERIAL9[numMaterials];

for(DWORD i = 0; i < numMaterials; i++) // for each material...
{
arraynew[i] = tempMaterials[i].MatD3D; // get the material
info
arraynew[i].Ambient = material[i].Diffuse; // make ambient
the same as diffuse
}

return;

so far the path parameter works. you can put any character string that
is a filename into it. ex: "mymeshfile.x"
i want to do the same sort of thing for creating an array.

*I want to be able to call the function as many times i want to
without having to also put a declaration for each array at the top.
*basically i want a stand-alone function.
Then you might consider explaining a fairly simple question without
throwing in 30 lines of irrelevent code.
Your question is quite difficult to answer because we don't know if
the array to be used is static.

Can you declare a local variable or container and use it outside the
function?
no
Why? cause it ceases to exist once the function terminates (unless its
static)

Can you allocate a variable or container on the heap and return a
pointer to it?
yes, but you are responsible for its deallocation and it severely
complicates code

Can you declare an array and pass it by reference for a function to
access and modify (not modifying just a copy)?
yes

#include <iostream>

template< typename N, const size_t Size >
void initialize(N (& r)[Size]) // pass array by reference
{
for( size_t t = 0; t < Size; ++t)
{
r[t] = t;
}
}

template< typename N, const size_t Size >
void display(const N (& r)[Size])
{
std::cout << "array size = " << Size;
for( size_t t = 0; t < Size; ++t)
{
std::cout << "\nr[" << t;
std::cout << "] = " << r[t];
}
std::cout << std::endl;
}

int main()
{
int array[8];
initialize(array);
// do work with array
display(array);
}

/*
array size = 8
r[0] = 0
r[1] = 1
r[2] = 2
r[3] = 3
r[4] = 4
r[5] = 5
r[6] = 6
r[7] = 7
*/

___
There has to be an easier way to do this?
yes there is - stop using primitive containers

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

template< typename T >
void initialize(std::vector< T >& r_v)
{
// std::generate is a better option
for(size_t t = 0; t < r_v.size(); ++t)
{
r_v[t] = t;
}
}

template< typename T >
std::ostream&
operator<<(std::ostream& os, const std::vector< T >& r_v)
{
std::copy( r_v.begin(),
r_v.end(),
std::ostream_iterator< T >(os, "\n") );
return os;
}

int main()
{
std::vector< int vn(8);
initialize(vn);
std::cout << vn;
}

/*
0
1
2
3
4
5
6
7
*/
Apr 17 '07 #10
On Apr 17, 5:58 am, Justcallmedr...@yahoo.com wrote:
How would you declare and assign a variable inside a function THAT HAS
THE NAME OF A PARAMETER YOU PASSED

example:
when you call createvariable("myvariable")

it will declare the variable "myvariable"
and then maybe assign it something.
myvariable = "this is a real variable"

also so you can use it later, outside of the function.
Hello,

You are trying achieve one more level of generalization on Language.
Its like, you want your own variable generation at runtime!

1) If your variable type is fixed, i.e. you need just String type..--
You can create std::map<string, stringvarMap
varMap["myvariable1"] = "1st variable";
varMap["myvariable2"] = "2nd variable";

at any time, you cat get your variable.

2) If variable type is also not fixed, you must need add extra setup.

NOTE: Code written below is just explanation & Not compiled or
working!

union varValue{
string strValue;
int intValue;
}

enum varType {STRING, INT} //Again enum, i was advised yesterday that,
enum is part of fully OO.

struct variable {
varType type;
varValue value;
}

std::map<string, variablevariableTable;

variable var1, var2;
var1.type = STRING;
var1.value = "my string variable value";
variableTable["myVar1"] = var1;

var2.type = INT
var2.value = 10;
variableTable["myVar2"] = var2;

Now you can have anytime, your variable's type & its value known to
you at runtime.

But still, getting value from varibaleTable is complex job.
Either you need to remember that myVar2 is int & you would always
write,
int t1 = variableTable["myVar2"].value
string s1 = variableTable["myVar1"].value

Or you need to write function that can manage typecasting or throw
exception! Here i think the solution fail.
still it could be like this,
int i1 = getValue(variableTable["myVar1"], INT); //myVar1 is string!!

& getValue would throw exception when it checks that
variableTable["myVar1"].type != INT
Finally, above could be considered as non-standard programming
practice.
Vijay.

Apr 17 '07 #11
On Apr 17, 9:46 am, patelvij...@gmail.com wrote:
>
union varValue{
string strValue;
int intValue;
}
No, you can't do this: (think: when a instance of varValue goes out of
scope, what destructor if any should be called?).

Apr 17 '07 #12
On Apr 16, 8:58 pm, Justcallmedr...@yahoo.com wrote:
How would you declare and assign a variable inside a function THAT HAS
THE NAME OF A PARAMETER YOU PASSED

example:
when you call createvariable("myvariable")

it will declare the variable "myvariable"
and then maybe assign it something.
myvariable = "this is a real variable"

also so you can use it later, outside of the function.
I would recommend a hash table. You make it sound like you want self
modifying code on runtime. 'Hash tables' is more of a topic for
another group - it's not a C++ phenomenon.

Apr 18 '07 #13
On Apr 17, 4:42 pm, tragomaskhalos <dave.du.verg...@logicacmg.com>
wrote:
On Apr 17, 9:46 am, patelvij...@gmail.com wrote:
union varValue{
string strValue;
int intValue;
}

No, you can't do this: (think: when a instance of varValue goes out of
scope, what destructor if any should be called?).
Yes, thank you for pointing out union & Class object. So it must use
pointer now.
I tried to write whole code, here is working copy. Still it need extra
code to follow standard practice, i.e. auto_ptr, providing getValue
function.

#include <iostream>
#include <string>
#include <map>
using namespace std;

union varValue{
string* strValue;
int* intValue;
};

enum varType {STRING, INT}; //Again enum, i was advised yesterday
that, enum is part of fully OO.

struct variable {
varType type;
varValue value;
};

int main() {
map<string, variablevariableTable;

variable var1, var2;
var1.type = STRING;
string tmpStr = string("my string variable value");
var1.value.strValue = &tmpStr;
variableTable["myVar1"] = var1;

var2.type = INT;
int temp = 10;
var2.value.intValue = &temp;
variableTable["myVar2"] = var2;

cout << *variableTable["myVar2"].value.intValue << endl;
cout << *variableTable["myVar1"].value.strValue << endl;
}

Vijay.

Apr 18 '07 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: tertius | last post by:
Is there a better way to append certain chars in a string with a backslash that the example below? chr = "#$%^&_{}" # special chars to look out for str = "123 45^ & 00 0_" # string to...
125
by: Sarah Tanembaum | last post by:
Beside its an opensource and supported by community, what's the fundamental differences between PostgreSQL and those high-price commercial database (and some are bloated such as Oracle) from...
8
by: Lyn | last post by:
I am trying to get my head around the concept of default, special or empty values that appear in Access VBA, depending on data type. The Access Help is not much (help), and the manual that I have...
17
by: Carl Mercier | last post by:
Hi, Is it possible to use special characters like \n or \t in a VB.NET string, just like in C#? My guess is NO, but maybe there's something I don't know. If it's not possible, does anybody...
7
by: Ben Finney | last post by:
Howdy all, Ned Batchelder blogged about a debate over checking function parameters, and to what extent dynamic typing should be relied upon. I was one of many who commented, but I wrote what...
3
by: alex | last post by:
<script> var sd=function(){ return{ f1:function(){ alert('f1'); }, f2:function(){ alert('f2'); } }
9
by: Robbie Hatley | last post by:
Greetings, group. I just found a weird problem in a program where a variable declared in a {block} after a "case" keyword was being treated as having value 0 even though its actual value should...
1
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have...
19
by: Eric S. Johansson | last post by:
Almar Klein wrote: there's nothing like self interest to drive one's initiative. :-) 14 years with speech recognition and counting. I'm so looking to my 15th anniversary of being injured next...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.