I'm a ruby developer and its been long time since I've coded in C. I want to use a datatype in C which behaves like a symbol.
Is this possible?
Program asks user for name
User replies - "foobar"
Program declares an integer with the same name i.e.
int foobar;
Unlike in interpreted languages, C does not have a dictionary of variable names at runtime. There exist no variable names at runtime at all. Hence unfortunately it is impossible to do what you want in C.
It's not possible to do this in C without implementing your own symbol table to emulate the desired behavior (essentially, implementing your own micro-programming language).
No. C must know names at compile time.
The best you could do is create your own dictionary of names and values. Much work though.
What do you want to do with the username-as-variable once you have it? What kind of operations would you perform with or on your foobaf variable?
As others have suggested you could use a data structure to dynamically associate the user name with a piece of integer data but knowing what you want to do with it would help inform suggestions as to whether that's even necessary and which data structures and algorithms you might want to look at.
Related
So i have a header and source file containing an implementation for a vector. I want to use the vector to implement a heap. So I realized that I would want my functions to be specific to the class so I declared each one as static thinking I could do Vector::get(int n, Vector::Vector* vector) but apparently :: is not an operator in C and static just makes things private. Can anyone help me understand how I can make the correct encapsulation and not name all my get functions Heap_get or Vector_get?
C++ has namespaces and class specifiers to distinguish between things like that but, in C, names have to be unique.
It's a time honored tradition to simply use a (generally short) prefix for your code and hope you never have to integrate code from someone else that has used the same prefix.
So names like vecGet() or heapCreate() are exactly the way C developers do this.
Now you can do polymorphism in C but it's probably overkill for what you're trying to do.
Is it possible to refer to a variable using multiple names in C ? I know this could be done via pointers but is it possible without using pointers. Just like we use 'typedef' for multiple naming of data type, similar for Variables
I have a constant named FILTER_PROC_LOAD_INTERNSITY, How to refer to it using simple name like 'var1'.
you may want to use macros?
#define var1 FILTER_PROC_LOAD_INTERNSITY
but the question is: why?
one "thing" one responsibility. You do not want to baffle the reader of your code. The name of the Variable seems to be wrong in the first place, if you have the need to rename the name.
Edith:
what my problem with readability is expressed in this example
char *very_ugly_variable_name;
#define beautifulVariableName very_ugly_variable_name
void unmaintainable_old_function() {
print(very_ugly_variable_name);
}
void myOtherNewFunction() {
print(beautifulVariableName);
}
you do not grok in a moment, that very_ugly_variable_name and beautifulVariableName are the exact same (in namescope and in memory).
The C language does not seem to have references (to alias your variable) but you can use a pointer to that end: yourtype* var1 = &FILTER_PROC_LOAD_INTERNSITY and then use *var1 to get the value of your constant. But this doesn't look like a good idea - symbolic names in programs are much easier to read and understand.
Is it possible to determine the elements(name & datatype) in a structure(C language) in a library ? If yes, how to do it in C language ? If C language does not support it, Is it possible to get the structure elements by other tricks or is there any tool for it?
Do you mean find out when you are programming, or dynamically at runtime?
For the former, sure. Just find the .h file which you are including and you will find the struct definition there including all the fields.
For the latter, no, it is not possible. C compiles structs to machine code in such a way that all of this information is lost. For example, if you have a struct {int x, float y, int z}, and you have some code which says
a = mystruct.y
in the machine code, all that will remain is something like finding the pointer to mystruct, adding 4 to it (the size of the int), and reading 4 bytes from there, then doing some floating point operations to it. Neither the names nor the types of those struct fields will be accessible at all, and therefore, there is no way to find them out at runtime.
No, it isn't possible. C has no inbuilt reflection-style support.
If by "determine the elements of a structure" you mean "get the declaration of that structure type programmatically", then I do not believe that it is possible - at least not portably. Contrary to more modern languages like C++ ot Java, C does not keep type information in a form available to the actual program.
EDIT:
To clarify my comment about it being impossible "portably":
There could very well be some compiler+debugging format combination that would embed the necessary information in the object files that it produces, although I can't say I know of one. You could then, hypothetically, have the program open its own executable file and parse the debugging information. But this is a cumbersome and fragile approach, at best...
Why do you need to do something like that?
I have one requirement in C.
char abc[]="hello";
char hello[]="world";
Using abc whether we can get the hello variable's value in C.
I know it is possible in some of the languages like Perl, Php, Bash,.,
Is it possible in C?
Yes you are right , this is possible in some other language but not in C ,
since abc is a container which resides in a location (for ex: 1000) and hello is one more
container which resides in another location ( for ex : 2000 ) , so we have no contact between
these two arrays ,
we cannot make a value ( strings ) to point some other value.
so finally THIS IS NOT AT ALL POSSIBLE.
No, this is not possible in C without providing a string lookup table of some sort that could link variables with their names.
It's impossible in C, unlike in more dynamic languages like Perl or Python. However, it's important to keep in mind that even in those languages this isn't recommended. I haven't seen a snippet of code putting this to a good use yet. The eval methods available in dynamic languages are used sparingly, and not for dynamically grabbing variable names.
As soon as the C compiler has figured out where to store the underlying pointers, it forgets about the name you gave it. The dynamic languages solve it with a data structure like a hash map which allows you to store the pointers (value) under a key (the name).
Another option is to read in the debug information. This is only available if you compile your code with -g (gcc) or some other, compiler specific option. Note that the debug format is not standardized, so you'll need to figure out what your compiler uses and how to work with it.
It is not possible in C. It can be done in java by reflection in some cases.
POSIX has several functions that allows you to do it, assuming variable hello is global and isn't static:
void *handle = dlopen(NULL, RTLD_NOW);
// error handling omitted
printf("%s variable contains value %s", abc, (char *)dlsym(handle, abc));
dlsym() return value is casted to char * to suppress warning when using compilers that check format string for printf-alike functions.
And you need to make sure you've specified correct compiler options, e.g. -rdynamic -ldl in case of GCC.
Being a developer born and raised on OO, I was curious to hear how it's possible to avoid global state in a procedural program.
You can also write object-oriented code in C. You don't get all the C++ goodies and it's ugly, and you have to manually pass the this pointer (I've seen self used for this, in order to make it compatible with C++), but it works. So technically, you don't need global state in pure procedural languages for the very same reasons you don't need it in object-oriented languages. You just have to pass the state around explicitly, rather than implicitly like in OO languages.
As an example, look at how the file I/O functions in the C standard library work with pointer to FILE objects that are (largely) opaque. Or look at how OS APIs deal with handles and such to encapsulate information. A program creates objects, uses APIs that act on those objects and closes/deletes the objects - all using straight C.
A global variable is nothing but an implicit procedure argument. Make it explicit and the global variable goes away.
Note: the fact that you no longer use a global variable does not mean that you no longer use global state! What we did above was just a purely syntactical transformation, the semantics of the program haven't changed at all. It's just as non-composable, non-modular, non-threadsafe, non-parallelizable as it was before.
All OO is a mindset and a whole bunch of compiler support.
You can achieve much the same by discipline, coding conventions, and passing around structures in most languages.
For example I used to have functions/procedures prefixed with their module identity, taking the first parameter as being the related module struct.
// System.h
typedef struct _System
{
struct _System *owner;
LinkedList *elements;
} System;
// System.c
int System_FindName ( System * system, char *name)
{
..
}
etc..
I'd really seriously not like to have to go back to coding like this though. I'm very happy that I haven't had to write and debug a linked list for at least 18 years. It was hard back then without the internet and sitting there isolated in the corner of a cold brightly lit room with green phosphors burning into your retina...
Of course. Just declare a struct somewhere, allocate some memory for it, pass the pointer to the allocated memory to an initialization function, and off you go. Just pass the pointer to all the functions that require using the struct.
Though the question arises as to where you store the pointer to the data you don't want to be global, and then you may end up with a global pointer ;-)
You can have variables on stack or in heap that will exist during all the program life.
Passing object style structure pointers to every function is a good way to have OO C coding style.
(I would suggest to have a look in linux sources)
You could try, as an example, create with dia (the diagramming tool), a simple class (for example, a square).
http://projects.gnome.org/dia/
http://dia-installer.de/index_en.html
Then, you can transform that class in C code using dia2code:
http://dia2code.sourceforge.net/
Specifically, say you created the class square inside the square.dia diagram. Then, you type:
$ dia2code -t c square.dia
... and you will see that it is possible to convert any object-oriented programming in a C program without global variables. Explore the created files square.c and square.h
NOTE: in Windows, you'll need a workaround in order to make dia2code work. Before using dia2code, change square.dia to square.zip, unzip it, and rename the result as square.dia
Simple. Whenever a procedure accesses a global variable, then give this variable as an argument to the procedure instead, either by value or by reference or by pointer, or by whatever your programming language provides. After that there is no more need for the variable to be global.