#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2012
    Posts
    7
    Rep Power
    0

    Post Concepts of auto and register keyword.


    Hi! I'm new to c programming and I often confused with keywords like auto and register. Well, I'm familiar with some of the basic concepts such as, if a variable is decleared as register then the value stored in a CPU register and can always be accessed faster than the one that is stored in memory.

    ==>But, how I could be sure that whether it is really stored in register memory or not. Cause, the number of CPU registers are limited, and they may be busy doing some other task.

    ==>In case of auto keyword, let an eample

    Code:
    int main ()
    {
    auto int i = 1 ;
    {
    auto int i = 2 ;
    {
    auto int i = 3 ;
    printf ( "\n%d ", i ) ;
    }
    printf ( "%d ", i ) ;
    }
    printf ( "%d", i ) ;
    return 0;
    }
    output : 321

    Code:
    int main ()
    {
    int i = 1 ;
    {
    int i = 2 ;
    {
    int i = 3 ;
    printf ( "\n%d ", i ) ;
    }
    printf ( "%d ", i ) ;
    }
    printf ( "%d", i ) ;
    return 0;
    }
    output : 321

    So, what is the basic concept in declearing a variabl as auto? Expecting an easily understandable answer. Thank you.
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,325
    Rep Power
    2227
    It's nice that you use code tags. Code tags are needed to preserve the indentation, and hence the formatting, of code lists. So indent your code, already!

    In 22 years of professionally programming in C and C++ (primarily in C), I have never ever even once used the auto keyword. All local variables are already auto by default, so using the keyword would be redundant and completely unnecessary. As is demonstrated by your two examples.

    What you are seeing is an issue of variable visibility, which is quite independent of use or non-use of the auto keyword. What is happening is that with each new code block (the space between two braces, { } ), declaring a new variable with the same name as one outside that new code block results in the outer variable being hidden. Therefore (please note the use of indentation to make the code readable):
    Code:
    int main ()
    {
        int i = 1 ;  // first i
        {
            int i = 2 ; // second i, hides the first i
            {
                int i = 3 ; // third i, hides the second i, which in turn hides the first
                printf ( "\n%d ", i ) ;  // prints the third i, the others not being visible
            }
            printf ( "%d ", i ) ;  // prints the second i, since the first i is hidden 
                                      //  and the third i no longer exists
        }
        printf ( "%d", i ) ;  // prints the first i; the second and third no longer exist
        return 0;
    }
    Now, as I assume you already know, declaring a local variable as static is very useful, because while it makes the variable only visible inside the function, it also lets it persist between function calls, so that whenever you call the function again, it will remember what it had been set to the last time.

    The register keyword is used only as a suggestion to the compiler, since it will not always be possible for the compiler to actually place it within a register. Its use, according to the ANSI C Standard (6.5.1), is that it "suggests that access to the object be as fast as possible."

    I have never used register, but I have seen it used especially in code that implements low-level functionality.
  4. #3
  5. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,782
    Rep Power
    4302
    Originally Posted by kitebird
    Well, I'm familiar with some of the basic concepts such as, if a variable is decleared as register then the value stored in a CPU register and can always be accessed faster than the one that is stored in memory.

    ==>But, how I could be sure that whether it is really stored in register memory or not. Cause, the number of CPU registers are limited, and they may be busy doing some other task.
    The register keyword is only a hint to the compiler that a certain variable should be placed in a CPU register. The compiler doesn't have to respect your suggestion at all. Compiler technology has improved since the good ol' days and most modern C compilers do a pretty good job of optimizing code and automatically figure out which variables should be placed in registers, even when you don't use the register keyword.

    Originally Posted by kitebird
    So, what is the basic concept in declearing a variabl as auto? Expecting an easily understandable answer. Thank you.
    In the C standard, auto is the default for local variable declarations, so most code doesn't use it at all. The following three lines are equivalent.
    Code:
    int i;
    auto int i;
    auto i;
    The opposite of auto is static, which you can see used in some code. dwise has already explained what the two do.

    It might be worthwhile to mention that since practically no one uses the auto keyword in their code, the new C++ standard has overloaded it with extra functionality which actually makes it useful.

    Earlier, if a function returned a value of a certain type, you were required to declare a variable of the type. For example:
    Code:
    int max_count = object.getLineCount();
    Of course, with C++ and namespaces, things could get slightly out of hand. For instance, if trying to get the number of items in a vector object, you need to declare something like this:
    Code:
    std::vector<std::string>::size_type max_len = myvector.size();
    In the new C++ standard, you can use the auto keyword like this:
    Code:
    auto max_count = object.getLineCount();
    auto max_len = myvector.size();
    what the C++ compiler does is look at the return type of object.getLineCount() and myvector.size() and automatically declare max_count and max_len to be the appropriate return types. Saves a ton of typing and you don't really need to change any of the declarations if you change the return type of object.getLineCount() later on, for instance.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  6. #4
  7. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,119
    Rep Power
    1807
    auto is implicit and never needed explicitly. It remains a reserved word in C but has no real purpose.

    Both register and auto are deprecated, and serve no purpose whatsoever.

    Contrary to your assumption that "if a variable is declared as register then the value stored in a CPU register and can always be accessed faster than the one that is stored in memory", the register modifier is (or rather was) merely a "hint" to the compiler, and modern compilers invariably simply ignore it on the basis that typically the compiler is better at deciding how to store and maintain variables that you are, and will optimise accordingly.

    In short you are wasting your time even worrying about these keywords.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2012
    Posts
    7
    Rep Power
    0

    Exclamation


    I appreciate you all for your help and it helped me to be clear.

    Here, i'm just asking, as you say

    The register keyword is used only as a suggestion to the compiler, since it will not always be possible for the compiler to actually place it within a register. Its use, according to the ANSI C Standard (6.5.1), is that it "suggests that access to the object be as fast as possible."
    If it doesn't really store data(s) in CPU memory then how compilers make fast execution as maximum as posible the certain variable which is defined as "register" than other variables, where entire code stores and runs from primary memory during execution?

    And in what case the "register" keyword is usefull?
  10. #6
  11. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    248
    As mentioned before, using the keyword is for all practical purposes useless in modern compilers. It is a legacy from the old days when compilers were a lot less sophisticated and programmers had a great deal more familiarity with hardware since they had extensive experience working with assembler. Just ignore it except for any test questions.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  12. #7
  13. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,487
    Rep Power
    1876
    > And in what case the "register" keyword is usefull?
    Well that depends on how you define "useful"

    The only aspect of register which you're going to reliably notice is that it will prevent you making a pointer to an object declared register.

    Eg.
    Code:
    register int foo;
    int *p = &foo;  // nope - can't do that.
    40 years ago, when C was first invented, and the compiler was capable of little more than a rather literal translation of the source code, then register was a useful tool for those who knew what would happen.

    Uninformed newbie programmers just sprinkled it everywhere like it was some kind of magic pixie dust, without really understanding that declaring 10 variables with 'register' when the real machine had only 4 registers was a complete and utter waste of time.

    But nowadays, there are dozens of different optimisation options, which do many more things than just decide whether to store 'x' in memory or a register.

    What is more, this happens EVERY time you compile the code. Using register was a 1-shot guess by the programmer - maybe it was OK in the version they edited, but 5 years on, the original reason is lost and now it doesn't make any difference at all.

    Leave the register assignment fiddling to the compiler - it's very good at it.
    Instead, focus on real performance gains like choosing the best algorithms and data structures for the problem at hand.

    For sure, if you choose "bubble sort" when you should have chosen "quicksort", then NO amount of register use or compiler options will save you from a long and pointless wait for results.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    2
    Rep Power
    0

    auto and register


    auto means the variable is automatic.Its lifetime and visibility is a function where it is declared.

    register is similar to auto but values are stored in cpu registers.
    register variables executes faster than memory variables

    Comments on this post

    • mitakeet disagrees : You have added exactly zero to this thread!

IMN logo majestic logo threadwatch logo seochat tools logo