A reusable variable: still good to define in the scope that uses it?

  • Context:
  • Thread starter Thread starter SlurrerOfSpeech
  • Start date Start date
  • Tags Tags
    Scope Variable
Click For Summary

Discussion Overview

The discussion revolves around the best practices for variable scope in C programming, specifically whether to define a variable within a loop or outside of it. Participants explore the implications of each approach in terms of efficiency, readability, and potential for errors.

Discussion Character

  • Debate/contested
  • Technical explanation
  • Conceptual clarification

Main Points Raised

  • Some participants argue that defining the variable within the loop is a best practice since it limits its scope and improves readability.
  • Others contend that defining the variable outside the loop is more efficient as it avoids re-initialization during each iteration.
  • A participant challenges the efficiency argument, stating that the difference is only in declaration, not initialization, and suggests that the first approach is preferable.
  • Concerns are raised about the complexity of the code, particularly regarding operator precedence and potential for errors, especially with the expression *c++==*s2++.
  • Some participants emphasize the importance of initializing variables to prevent undefined behavior, especially when the loop may not execute.
  • One participant mentions the "least privilege" principle, advocating for local scope to minimize the risk of unintended modifications.
  • Another participant suggests that using standard library functions could simplify the task at hand, hinting at alternatives like strcmp().

Areas of Agreement / Disagreement

Participants express differing views on the best practice for variable scope, with no consensus reached on whether to define variables inside or outside of loops. The discussion includes both technical arguments and personal preferences, indicating a lack of agreement on the optimal approach.

Contextual Notes

Some participants note that the code examples provided may lead to undefined behavior under certain conditions, highlighting the importance of careful variable initialization and scope management.

SlurrerOfSpeech
Messages
141
Reaction score
11
I'll give you an example.

Let's say I have a snippet of code like

Code:
   while(*s2)
   {
       char* c = s1;
       while(*c++==*s2++);
       if(!*c)
       {
          flag=true;
          break;
       }
       else
       {
          flag=false;
       }
   }

(which is a real snippet of code I have).

One might alternatively write it like

Code:
    char* c;
   while(*s2)
   {
       c = s1;
       while(*c++==*s2++);
       if(!*c)
       {
          flag=true;
          break;
       }
       else
       {
          flag=false;
       }
   }

The main argument I can see for the first way is

"The variable c is only used in the while loop and therefore should be defined there as best practice."

The main argument I can see for the second way is

"It's equiavlent and more efficient because you don't have to initialize c during every iteration of the while loop."

What are your thoughts?
 
Last edited by a moderator:
Technology news on Phys.org
SlurrerOfSpeech said:
The main argument I can see for the second way is

"It's equiavlent and more efficient because you don't have to initialize c during every iteration of the while loop."
This is not a correct statement. In both cases, what changes is where c is declared, not initialized. After compilation, there will be no difference between the two pieces of code. The first approach is preferable.
 
  • Like
Likes   Reactions: FactChecker
You can verify DrClaude's claim easily at http://gcc.godbolt.org/. It is a very convenient tool for showing how your code maps to the machine.

(In many cases, it will also show just how much work your compiler does for you. This can give you confidence in writing the clearest code you can think of, and leaving micro-optimization to the compiler. It's usually much better at it than you. Modern optimizing compilers are remarkable.)
 
  • Like
Likes   Reactions: FactChecker and DrClaude
The only advantage for c being defined outside of the loop is if you need to reference later on outside of the loop.

In either case, the code you've shown gives me a headache as you have to remember the operator precedence for the more arcane C operators and its easy to get it wrong. I especially hate the expression: *c++==*s2++
 
  • Like
Likes   Reactions: Samy_A
jedishrfu said:
I especially hate the expression: *c++==*s2++
Good lord. Yeah, at least get some parenthesis in there.Uhh... your code is incorrect. That can also go pass the null terminator easily if the strings are the same length.
 
  • Like
Likes   Reactions: jedishrfu
DrClaude said:
This is not a correct statement. In both cases, what changes is where c is declared, not initialized. After compilation, there will be no difference between the two pieces of code. The first approach is preferable.

Sorry, the mord I meant to use is instantiated.
 
jedishrfu said:
The only advantage for c being defined outside of the loop is if you need to reference later on outside of the loop
Bad idea, I could cause that to give you undefined behavior by setting s2 = ""; If your planning on using something outside of a loop that may run 0-n times, you should always initialize it. I like to initialize my variables outside of loops even if I'm 100% sure it'll run at least once, it prevents me from messing things up if I refactor it later.
 
Hint: smashing things together in one line of code is all of these: cool, hard to read, more prone to problems.
So, what do you gain: cool? Not cool actually.

Quite simply: Don't do that. The compiler will undo it anyway. Follow the advice @Integrand gave you.

Plus I would suggest very strongly that you learn the standard C library, one member of which does what it appears your code :nb) tries to do.
See if you can tell us which one that is. Try the string section, you know strcmp() and friends.
 
It is a question of the well known software engineering "least privilege" principle: at every function or construct for procedural code and their counterparts in OOP, you must always give a variable the least chance to be modified by the rest of your code or so to speak, you always have to begin in local scope and expand to the "outside" only for very good reasons.
 
  • Like
Likes   Reactions: FactChecker
  • #10
newjerseyrunner said:
Bad idea, I could cause that to give you undefined behavior by setting s2 = ""; If your planning on using something outside of a loop that may run 0-n times, you should always initialize it. I like to initialize my variables outside of loops even if I'm 100% sure it'll run at least once, it prevents me from messing things up if I refactor it later.

I didn't mean not to initialize it only that if you need it later then you promote it to the next higher scope. I figured it wasn't apparent as often posters don't post all of their code.
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
Replies
5
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 32 ·
2
Replies
32
Views
4K
  • · Replies 75 ·
3
Replies
75
Views
7K
Replies
1
Views
4K
  • · Replies 18 ·
Replies
18
Views
4K