简体   繁体   中英

Difference between const variable and const type variable

What is the difference between:

const variable = 10;

and

const int variable = 10;

Does variable, per the standard, get interpreted as an integral type when no type is defined?

const variable = 10 is not valid C++, while const int variable = 10; is.

The only time (that I can think of) that const variable = 10 would be valid is if you had a type named variable and you had a function with an unnamed parameter of that type, taking a default argument:

typedef int variable;
void foo(const variable = 10);

It means that x is implicitly declared an int. This is not allowed in C++, but in C and to maintain compatibility with C headers or pre-ISO C++ code, a lot of contemporary C++compilers still support this as an option.

My GCC 4.4 compiler here groks "const x=3;" when feed -fms-extensions on the command line (the manual says, that it turns on a couple of lamps which are required to understand MFC code)

UPDATE: I've checked it with VS-2005, you can have implicit int if you use

#pragma warning(disable:4430)
const variable = 10;

几乎所有新的现代C ++编译器都不会编译。

With no strict rules (K&R C etc. Edit : ie old C), int is the type by default. It certainly does not mean the variable has no type, and it does not have anything to do with const.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM