Thread: when to declare function variables inside vs. outside of curly brackets

  1. #1
    Registered User zolfaghar's Avatar
    Join Date
    Mar 2016

    when to declare function variables inside vs. outside of curly brackets

    I am reading "let us C" book, and going through the exercises at the end of chapter 5. and part H has two exercises, a and c. The answer to one states that the variable should be declared within the brackets of the function and the other states that it should be done outside. I assume it has to do with the scope of the variable. Could someone please elaborate on this? I like to validate my understanding and know all the details that govern when to declare a variable.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Yes, the former is declared in a local scope; the latter is declared at file scope: it would be a global variable unless declared static, in which case it would be restricted to the translation unit (headers + source file). Generally, you should limit the scope of your variables to the smallest scope necessary.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. IF Statement-- With curly brackets or semicolon
    By erdemtuna in forum C Programming
    Replies: 6
    Last Post: 01-10-2016, 06:40 AM
  2. Declare variables inside loops the right way?
    By anthonyemuobo in forum C++ Programming
    Replies: 3
    Last Post: 05-05-2015, 03:50 PM
  3. Replies: 2
    Last Post: 03-11-2015, 05:20 AM
  4. static variables inside a function.
    By theju112 in forum C Programming
    Replies: 13
    Last Post: 08-17-2011, 05:54 AM
  5. declare function inside fork()
    By MK27 in forum C Programming
    Replies: 35
    Last Post: 02-03-2009, 06:56 PM