Code Doodles #1 – this code is legit… again

The following is a legit, albeit a little obscure, C89 program. It is also a legit C++11 (and above) program.

int main(void)
	auto a = 42;
	return 0;

In C89, auto is used as storage specifier and a‘s type is (implicitly) int. C++ and C (beginning with C99) forbid implicit int declarations, but C++11 changes the meaning of the keyword auto from an automatic storage specifier (which is, conveniently, the default in function scope) to automatically deduced type. 42 is an integer literal (and a pretty good answer, from what I understand), so the deduced type is int (also C89’s default). The following table describes how different versions of C and C++ interpret auto a = 42; in a function scope:

C89 C99 C11 C++03 C++11
Storage specifier explicit auto* explicit auto* explicit auto* explicit auto* implicit auto
Type implicit int none none none automatically deduced int
Result int with automatic storage duration code incorrect code incorrect code incorrect int with automatic storage duration

*also the default

In the end, it means the exact same thing in C++11 and C89, but for completely different reasons.

One thought on “Code Doodles #1 – this code is legit… again

  1. Howdy! I could have sworn I’ve been to this site before but after browsing through a few of the posts I realized
    it’s new to me. Regardless, I’m certainly delighted I
    found it and I’ll be book-marking it and checking back frequently!

Leave a Reply

Your email address will not be published.