13

Use case of storage class identifier auto?I understand that all local variables are auto by default. But whats makes difference by writing explicitly auto int a ?

vkesh
  • 269
  • 2
  • 3
  • 5

4 Answers4

12

There is strictly no difference.

{
   auto int a;
   /* ... */
}

and

{
   int a;
   /* ... */   
}

are equivalent.

The common practice is not to put the auto specifier.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • I could find this every where then it means there is no special significance of auto keyword. – vkesh Mar 29 '13 at 15:02
  • 1
    @vkesh That is correct for C. "`auto`" means "not `static`", which is the default. It had more influence in its predecessor B. http://en.wikipedia.org/wiki/B_(programming_language) – Drew Dormann Mar 29 '13 at 15:04
  • Are they equivalent or exactly the same? – Sam Mar 29 '13 at 15:54
3

There are two possible cases:

  1. auto is the default, and explicitly adding the keyword accomplishes nothing
  2. auto isn't allowed (e.g., on a global variable) in which case adding auto prevents the code from compiling
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Did you mean by the second possible case that if we add auto to global variable prevents the global variable being defined?? If so whats the usecase if you know anything? – vkesh Mar 29 '13 at 15:07
  • 1
    @vkesh: I'm saying if you try to specify `auto` for a global variable, the code won't compile (with a properly functioning compiler, anyway). As far as "what's the use-case", my point is that there is none. – Jerry Coffin Mar 29 '13 at 15:09
3

In modern day C (C89, C99, C11), the auto keyword is redundant. Other than making intent explicit ("This is a non-static variable, and I mean it!"), it serves no longer any purpose. It is a remnant of C history, carried over from B, but much like the entry keyword has become practically obsolete.

I used it once in my life. It was in an IOCCC entry in conjunction with implicit int:

 drive () { auto motive; ... }
Jens
  • 69,818
  • 15
  • 125
  • 179
1

There is little bit difference between a local variable and auto variable.

we can make local variable int a=20; to any storage class variable like auto int a=20; or static int a=20; but once when we specify any variable to auto like auto int a=20; then it will never become other storage class like static or register etc. we can not write like static auto int a=20;.other things are exactly same like Both got memory in stack segment. Below is the example of auto variable which generates same output.

for auto variable.

#include<stdio.h>
int fun()
{
        auto int a=20;
        printf("%d\n",a);
        a++;
        return 0;
}
int main()
{       
        fun();
        fun();
        return 0;
}

for Local variable.

#include<stdio.h>
int fun()
{
        int a=20;
        printf("%d\n",a);
        a++;
        return 0;
}
int main()
{       
        fun();
        fun();
        return 0;
}
Gambler Aziz
  • 41
  • 1
  • 10