Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

#define vs. const 1

Status
Not open for further replies.

JasonWB007

Programmer
Dec 21, 2005
14
US
Hi everyone,

Sometimes, I have need for a #define that really only applies to a single subroutine, so I would like to keep it with that routine. In general, I believe that #defines go at the top of a C file, so is there a good "proper" way to place the #define within the C routine? Should I simply declare a variable as const?

Thanks,

Jason
 
You can place #defines anywhere you like, but the scope is always from that point until the end of the file.
Code:
void foo ( ) {
#define MSG "hello"
  printf("%s",MSG);
}
void bar ( ) {
  printf("%s",MSG);
}
bar would print hello as well.

You can create a scope illusion with lots of undefs, like so
Code:
void foo ( ) {
#define MSG "hello"
  printf("%s",MSG);
#undef MSG
}
void bar ( ) {
#define MSG "world"
  printf("%s",MSG);
#undef MSG
}

> Should I simply declare a variable as const?
If you can, you should. const things are type checked for one thing.
Sometimes you have no choice, this for example isn't legal C code.
Code:
void foo ( ) {
  const int SIZE = 10; /* must be a #define */
  int array[SIZE];
}

--
 
What advantage is there for a [tt]#define[/tt] that is only used in one place? Could you post an example that might make things clearer?
 
Thanks for the reply. I will probably put the #define as you show. Please note that I am not intentionally *limiting* the scope, I just like having it physically close together. My question, I guess, was more about what is "proper" programming procedure and if:

int function(int var)
#define blah_blah 10
{
code
}

would be considered "sloppy" programming.
 
I avoid #define's as much as possible in favor of const variables. Const variables help with type checking, limit scope, don't add even more preprocessor definitions, and can save space by not copying code everywhere it's used.
Example:
Code:
void function( void )
{
   const char str[] = "Hello World";
   printf( "%s", str );
   MakeUpperCase( str );
   printf( "%s", str );
}
If the code above would have used #define for the string instead of const char, it would have needlessly replicated the string "Hello World" 3 times instead of once.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top