is it fine to use auto keyword in function parameter?

1.2k views Asked by At

I know that meaning of auto keyword has been changed completely from C++11. But Recently I wrote a following simple program that compiles & runs fine when compiling with =std=c++98 option.

#include <iostream>
void fun(auto int a)
{   
    a=3;
    std::cout<<a<<'\n';
}
int main()
{
    fun(3);
}

Orwell Dev C++ IDE gives me warning like following:

[Warning] 'auto' changes meaning in C++11; please remove it [-Wc++0x-compat]

So, is it fine to use auto for function parameters or should I never use auto like this as in above program to maintain compatibility with C++11?

3

There are 3 answers

1
Jens On BEST ANSWER

Until C++ 11 the auto keyword was a "storage class specifier" whereas with C++ 11 it becomes a type-induction specifier.

To answer your question: depending on the C++ standard you use to compile your code, adjust the use of the auto keyword accordingly. It's not portable across the pre/post C++ 11 boundary of the C++ standard.

0
Yakk - Adam Nevraumont On

auto prior to C++11 was a storage class specifier, like register or static or extern.

It, however, was the default storage class specifier. Valid C++03 code with it removed would have the same meaning, which is why C++11 felt comfortable stealing the keyword.

In short:

void fun1(auto int a) {   
  std::cout<<a<<'\n';
}
void fun2(int a) {   
  std::cout<<a<<'\n';
}

have the same meaning in C++03. In C++11, fun1 is ill-formed.

Simply remove it from all of your pre-C++11 codebases. If the code was valid C++03, it will continue to have the same meaning.

There is a (very small) problem that some compilers might implement the K&R era C "by default, a type is int". Ie, they might consider auto x; to mean auto int x;. This was not valid C++03, however. Compiling with sufficiently strict flags in C++03 mode should generate errors around that (ab)use of auto.

As an aside, C++11 also introduces a new storage class specifier, thread_local. It steals auto for the use of auto-typed variables, and auto is no longer a storage class specifier.

0
utnapistim On

So, is it fine to use auto for function parameters or should I never use auto like this as in above program to maintain compatibility with C++11?

That depends on what you mean by "fine":

If you mean "will it compile?" then YES.

If you mean "is it a good practice", the answer is that it is not a practice at all; It was possible to do so and the code was perfectly valid (before C++11) but that time is passed, and I do not know of anyone who did this (not even for tricky interview questions).

In conclusion, don't do it.