Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a common practice to re-use the same buffer name for various things in C?

Tags:

c

naming

buffer

For example, suppose I have a buffer called char journal_name[25] which I use to store the journal name. Now suppose a few lines later in the code I want to store someone's name into a buffer. Should I go char person_name[25] or just reuse the journal_name[25]?

The trouble is that everyone who reads the code (and me too after a few weeks) has to understand journal_name is now actually person_name.

But the counter argument is that having two buffers increases space usage. So better to use one.

What do you think about this problem?

Thanks, Boda Cydo.

like image 471
bodacydo Avatar asked Aug 15 '10 20:08

bodacydo


2 Answers

The way to solve this in the C way, if you really don't want to waste memory, is to use blocks to scope the buffers:

int main()
{
  {
    char journal_name[26];
    // use journal name
  }
  {
    char person_name[26];
    // use person name 
  }
}

The compiler will reuse the same memory location for both, while giving you a perfectly legible name.

As an alternative, call it name and use it for both <.<

like image 175
Blindy Avatar answered Nov 06 '22 18:11

Blindy


Some code is really in order here. However a couple of points to note:

Keep the identifier decoupled from your objects. Call it scratchpad or anything. Also, by the looks of it, this character array is not dynamically allocated. Which means you have to allocate a large enough scratch-pad to be able to reuse them.

An even better approach is to probably make your functions shorter: One function should ideally do one thing at a time. See if you can break up and still face the issue.

like image 32
dirkgently Avatar answered Nov 06 '22 19:11

dirkgently