Re: Using define with variable values



msigwald@xxxxxxxxx wrote:

The following line of code works, however, since my professor is a real
purist of c, I would like to know if this code is valid (is it good
code or a piece of crap?):
#define  DMP_FILE   argv[argc-1]

This would be use to do something like this:
void main(int argc,char *argv[])
{
     FILE *p2file=fopen(DMP_FILE,"w");
}

Is this a macro? Cause in the examples of macro I've studied, variables
were involved in the macro itself. This would be like a regular define,
but with variable values.

The macro definition is valid, and the expansion is what you intended. However, it's "fragile" because it relies on the particular names `argc' and `argv' -- and although these are very often used as the names of the arguments of main(), other names are permissible:

	int main(int zaphod, char **just_this_guy) {
	    time_t argv = time(NULL);
	    clock_t argc = clock();
	    ...

is perfectly valid, but would play havoc with your macro.
If you're sure that no one who uses your macro will ever
do anything so stupidly perverse, fine -- but it's usually
best not to "build in" such dependencies.  Your macro will
work, but it's probably not Best Practice.

    However, your purist professor may not even bother with
the possible shortcomings of the macro, since you've given
him two count them two bona-fide errors to fixate on.  Walter
Roberson already pointed out one of them; you may discover
the other by a careful examination of the differences between
your main() and the main() in my reply.

--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxx

.



Relevant Pages