refer to a variable using multiple names in C - c

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.

Related

Is it possible to get a function name without invoking it?

How can i get a function's name without calling/invoking it, or is that even possible ?
I have an array of sorting functions, my goal is to be able to list the name of each one, dynamically, without having to invoke any.
After searching on the web, i couldn't find any solution that doesn't require the function being invoked and uses __FUNCTION__ or __func__.
The array of functions that is use:
// Pointer to functions
char *(*srtFunc[])(int *, int) = {selection, bubble, recursiveBubble, insertion, recursiveInsertion};
More information about what I want to achieve with this:
I want to loop over each function in the given array, create a file with the name of the function, invoke the function 100 times with different arguments each time, and print the time spent by the function each time in its dedicated file, redo for the remaining functions.
Unfortunately, not easily. C is not built for introspection and doesn't have features like this-- the name of function foo and the call to function foo are compiled down to just some jump and call instructions in the output; the actual name "foo" is essentially a convenience for you when programming and disappears in the compiled output.
The macro __FUNCTION__ is a preprocessor macro-- and as you note it only works within a function, because all it does it tell the preprocessor (as its churning through the text) hey, as you're scanning this token just drop in the name of the function you're currently scanning and then continue on. It's very "dumb" and is upstream of even the compiler.
There are various ways to get the effective result you want here, including most simply just manually building a table of string literals that have the same names as your functions. You can do this in fairly clean ways (see #nielsen's answer for a useful snippet) using macros. But the preprocessor/compiler can't help you derive or enforce a table from the actual functions so you will always have some risk of an issue at runtime when you make changes to it. Unfortunately C just doesn't have the capability for the kind of elegance you're looking for in this design.
You may be able to do something with smart preprocessor tricks, but your code would be difficult to read. I think I would go for the really low-tech solution here and just add an array of the function names matching the array of function pointers:
#define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))
// Pointer to functions
char *(*srtFunc[])(int *, int) = {selection, bubble, recursiveBubble, insertion, recursiveInsertion};
const char *srtFuncNames[] = {"selection", "bubble", "recursiveBubble", "insertion", "recursiveInsertion"};
_Static_assert(ARRAY_SIZE(srtFuncNames)==ARRAY_SIZE(srtFunc), "Function table and names out of synch!");
Having the two definitions just after each other makes it easy to keep them synchronized and the code is easy to read. The _Static_assert (available from C11) will help remembering to add new names as new functions are added.
Alternatively, a structure can be defined holding a function pointer and corresponding name. This can be initialized using a macro as follows:
typedef struct
{
char *(*srtFunc)(int *, int);
const char *srtName;
} sortMethod;
#define SORT_METHOD(S) {(S), #S}
sortMethod methods[] = {
SORT_METHOD(selection),
SORT_METHOD(bubble),
SORT_METHOD(recursiveBubble),
SORT_METHOD(insertion),
SORT_METHOD(recursiveInsertion)
};

#define for pedagogical purposes

I would like to hide some complexity from some non-trivial code I'm writing. Here, I would like to hide one level of indirection from a struct pointer, to make it more readable. I'm not asking whether this is clean or a best practice or not, I know it isn't, but I also know what I like to achieve :)
So, how kosher is to have something like
#define getmark() m->o->marked
besides that fact that I would not write it in non-academic code? That would allow me to do
n->getmark()
, which is nicer (and more to the point than)
n->m->o->marked
Is the #define code correct? Will it just do a text replace here with no other strings attached?
IMHO, most C programmers would prefer a function-style macro, like:
#define getmark(m) ((m) && (m)->o ? (m)->o->marked : -1)
Quite frankly - not.
You are not making your code eaiser to read, but instead hiding the fact that there is a hidden state machine (m pointer which points to o).
You also make this hack global - which might break if someone has such variables.
Also ... the trick of adding "()" after the macro to make it look like you are calling a normal function, instead of 2 indirections... is bad. It looks for a reader like there should be a function with this name, but instead you hide a monster (poker face....).
If you need to simplify the state machine, and you know that there will be only one state - create a global static variable and create plain functions to call those objects.
It will work, but even in C it's a terrible idea. Please don't do it.
If you want to avoid the 'source bloat' of repeated indirections, use a temporary pointer.
O* myO;
myO = n->m->o;
o->marked = o->this + o->that;
A problem with your original macro is that
n->getmark() = 123;
will work while it should not.

Dynamic variable declaration in C

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.

Getting Variable dynamic in c

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.

Defining const values in C

I have a C project where all code is organized in *.c/*.h file pairs, and I need to define a constant value in one file, which will be however also be used in other files. How should I declare and define this value?
Should it be as static const ... in the *.h file? As extern const ... in the *.h file and defined in the *.c file? In what way does it matter if the value is not a primitive datatype (int, double, etc), but a char * or a struct? (Though in my case it is a double.)
Defining stuff inside *.h files doesn't seem like a good idea generally; one should declare things in the *.h file, but define them in the *.c file. However, the extern const ... approach seems inefficient, as the compiler wouldn't be able to inline the value, it instead having to be accessed via its address all the time.
I guess the essence of this question is: Should one define static const ... values in *.h files in C, in order to use them in more that one place?
The rule I follow is to only declare things in H files and define them in C files. You can declare and define in a single C file, assuming it will only be used in that file.
By declaration, I mean notify the compiler of its existence but don't allocate space for it. This includes #define, typedef, extern int x, and so on.
Definitions assign values to declarations and allocate space for them, such as int x and const int x. This includes function definitions; including these in header files frequently lead to wasted code space.
I've seen too many junior programmers get confused when they put const int x = 7; in a header file and then wonder why they get a link error for x being defined more than once. I think at a bare minimum, you would need static const int x so as to avoid this problem.
I wouldn't be too worried about the speed of the code. The main issue with computers (in terms of speed and cost) long ago shifted from execution speed to ease of development.
If you need constants (real, compile time constants) you can do that three ways, putting them into header files (there is nothing bad with that):
enum {
FOO_SIZE = 1234,
BAR_SIZE = 5678
};
#define FOO_SIZE 1234
#define BAR_SIZE 5678
static const int FOO_SIZE = 1234;
static const int BAR_SIZE = 5678;
In C++, i tend to use the enum way, since it can be scoped into a namespace. For C, i use the macro. This basicially comes down to a matter of taste though. If you need floating point constants, you can't use the enumeration anymore. In C++ i use the last way, the static const double, in that case (note in C++ static would be redundant then; they would become static automatically since they are const). In C, i would keep using the macros.
It's a myth that using the third method will slow down your program in any way. I just prefer the enumeration since the values you get are rvalues - you can't get their address, which i regard as an added safety. In addition, there is much less boiler-plate code written. The eye is concentrated on the constants.
Do you really have a need to worry about the advantage of inline? Unless you're writing embedded code, stick to readability. If it's really a magic number of something, I'd use a define; I think const is better for things like const version strings and modifying function call arguments. That said, the define in .c, declare in .h rule is definitely a fairly universally accepted convention, and I wouldn't break it just because you might save a memory lookup.
As a general rule, you do not define things as static in a header. If you do define static variables in a header, each file that uses the header gets its own private copy of whatever is declared static, which is the antithesis of DRY principle: don't repeat yourself.
So, you should use an alternative. For integer types, using enum (defined in a header) is very powerful; it works well with debuggers too (though the better debuggers may be able to help with #define macro values too). For non-integer types, an extern declaration (optionally qualified with const) in the header and a single definition in one C file is usually the best way to go.
I'd like to see more context for your question. The type of the value is critical, but you've left it out. The meaning of the const keyword in C is quite subtle; for example
const char *p;
does not mean that pointer p is a constant; you can write p all you like. What you cannot write is the memory that p points to, and this stays true even as p's value changes. This is about the only case I really understand; in general, the meaning of the subtle placement of const eludes me. But this special case is extremely useful for function parameters because it extracts a promise from the function that the memory the argument points to will not be mutated.
There is one other special case everyone should know: integers. Almost always, constant, named integers should be defined in a .h file as enumeration literals. enum types not only allow you to group related constants together in a natural way, but also allow you the names of those constants to be seen in the debugger, which is a huge advantage.
I've written tens of thousands of lines of C; probably hundreds if I try to track it down. (wc ~/src/c/*.c says 85 thousand, but some of that is generated, and of course there's a lot of C code lurking elsewhere). Aside from the two cases about, I've never found much use for const. I would be pleased to learn a new, useful example.
I can give you an indirect answer. In C++ (as opposed to C) const implies static. Thatis to say in C++ static const is the same thing as const. So that tells you how that C++ standards body feels about the issue i.e. all consts should be static.
for autoconf environment:
You can always define constants in the configure file as well. AC_DEFINE() i guess is the macro to define across the entire build.
To answer the essence of your question:
You generally do NOT want to define a static variable in a header file.
This would cause you to have duplicated variables in each translation units (C files) that include the header.
variables in a header should really be declared extern since that is the implied visibility.
See this question for a good explanation.
Actually, the situation might not be so dire, as the compiler would probably convert a const type to a literal value. But you might not want to rely on that behavior, especially if optimizations are turned off.
In C++, you should always use
const int SOME_CONST = 17;
for constants and never
#define SOME_CONST 17
Defines will almost always come back and bite you later. Consts are in the language, and are strongly typed, so you won't get weird errors because of some hidden interaction. I would put the const in the appropriate header file. As long as it's #pragma once (or #ifndef x / #define x / #endif), you won't ever get any compile errors.
In vanilla C, you might have compatibility problems where you must use #defines.

Resources