Concept of “auto” keyword in c

吃可爱长大的小学妹 提交于 2019-11-30 05:02:07
Laurence Gonsalves

auto isn't a datatype. It's a storage class specifier, like static. It's basically the opposite of static when used on local variables and indicates that the variable's lifetime is equal to its scope (for example: when it goes out of scope it is automatically destroyed).

You never need to specify auto as the only places you're allowed to use it it is also the default.

It might be useful in C89 where you have an implicit int rule.

void f() {
  a = 0; // syntax error
  auto b = 0; // valid: parsed as declaration of b as an int
}

But then, you can just write straight int instead of auto. C99 doesn't have an implicit int rule anymore. So I don't think auto has any real purpose anymore. It's "just the default" storage specifier.

You get the auto behaviour by default whenever you declare a variable for example - int i = 0; However you do the same by explicitly specifying auto int i = 0 which is not needed.

As said auto is the default for variables in function scope in C. The only usage that I have had for the keyword is in macros. For a macro that does a variable declaration you might sometimes want to ensure that the variable is not declared static or in file scope. Here the auto keyword comes handy.

This was particularly useful for C++ where you could abuse the constructor/destructor mechanism to do scope bound resource management. Since the auto keyword is currently changing its meaning to something completely different in C++, this use is not possible any more.

I find that quote quite questionable. The logical level of a compiler has nothing to do with the logical level of the compiled language, even when the two languages are the same. May be I'm poor on fantasy but I really can't imagine how having or not a certain keyword can be useful for a compiler but not for a general program; especially in "C" where you cannot directly manipulate keywords or any form of code anyway and you've to reflect everything on data because, in "C", code and data are two completely distinct concepts.

My wild guess is that auto was there originally because it wasn't optional but mandatory, later when the language evolved and it wasn't necessary any more it still remained because of backward compatibility reasons with existing C code.

Suppose I have a function returning some kind of convoluted pointer to a complex structure or, as I am developing a function that could be returning different structures, I would like in C to have:

auto myautoptr=This_Function_that_returns_some_pointer_type();

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!