tags:

views:

156

answers:

3

Is a type specifier required here?

const c = 7;

Bjarne Stroustrup's 'The C++ Programming Language' on page 80 says that this is illegal. However, I've been practicing some brainbench tests, and one of the questions states that the type defaults to int. Brainbench is usually correct, so I'm unsure of which reference is right, and I've been unable to find anything in the standard. Does anyone have a definitive answer and a reference?

+13  A: 

The default type of int is valid for C, but not for C++. Even in C this style of coding should be avoided. Also note that Bjarne Stroustrup's book is one of the most authoritative reference for standard C++.

Vijay Mathew
The most authoritative short of the standard itself of course.
MSalters
@MSalters Agreed. Modified the post to reflect this.
Vijay Mathew
It seems a shame that this isn't legal code given that the C++0x (draft) standard is moving towards type inference: auto x = 7; // x is inferred to be an int from typeof(7)More info on Bjarne's FAQ: http://www.research.att.com/~bs/C++0xFAQ.html#auto
JBRWilkinson
Far from a shame: with auto, you show that you intend to let the compliler decide the type. Here, you might just have forgotten.
Pontus Gagge
+2  A: 

I can't speak to the standard... but just looking at a statement like const c = 7; screams bad code style to me. As far as compiler compatibility... it's probably going to be hit-and-miss. Microsoft Visual Studio's compiler won't have any part of it when compiling a C++ file (.cpp extension) but doesn't choke on it when compiling a C file (.c extension) mainly because the C standard allows for defaulting variables as int when no type is specified.

Adam Maras
Unfortunately these types of tests ask extremely esoteric things, facts that you would never rely upon if you were writing code (if you understand it, it's almost certain the next person wont!)
Taras
+3  A: 

For C++ I would believe Stroustrup over any place but a standard.

Perhaps the question was about C not C++?

The draft C++0x standard in section 7.1.6 says

At least one type-specifier that is not a cv-qualifier is required in a declaration unless it declares a constructor, destructor or conversion function.83 A type-specifier-seq shall not define a class or enumeration unless it appears in the type-id of an alias-declaration (7.1.3).

Mark