简体   繁体   English

const变量和const类型变量之间的区别

[英]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; const variable = 10是无效的C ++,而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: 唯一一次(我能想到) const variable = 10将是有效的是你有一个名为variable的类型,并且你有一个带有该类型的未命名参数的函数,采用默认参数:

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

It means that x is implicitly declared an int. 这意味着x被隐式声明为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. 这在C ++中是不允许的,但在C中并且为了保持与C头或ISO C ++前代码的兼容性,许多当代C ++编译器仍然支持这一选项。

My GCC 4.4 compiler here groks "const x=3;" 我的GCC 4.4编译器在这里修改“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) 当在命令行上输入-fms-extensions时(手册说,它打开了几个需要理解MFC代码的灯)

UPDATE: I've checked it with VS-2005, you can have implicit int if you use 更新:我已经用VS-2005检查了它,你可以使用隐式int

#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. 没有严格的规则(K&R C等编辑:即旧C),默认情况下int是类型。 It certainly does not mean the variable has no type, and it does not have anything to do with const. 它当然不意味着变量没有类型,它与const没有任何关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 静态变量和常量变量有什么区别? - What is the difference between a static and const variable? 静态const和constexpr变量有什么区别? - What is the difference between a static const and constexpr variable? 用 const 成员替换某个类型的变量 - Replace a variable of a type with const members 就其存储而言,C ++类中的静态const和const变量之间是否有区别? - Is there difference between a static const and const variable inside a c++ class in terms of its storage “type const &value”和“type const&value”之间有区别吗? - Is there a difference between 'type const &value' and 'type const& value'? const auto 和 const type 之间有什么区别* - what's difference between const auto and const type* 静态对const局部变量有影响吗? - Does static make a difference for a const local variable? 编写static const uint变量和匿名枚举变量有什么区别? - What is the difference between writing static const uint variable and anonymous enum variable? const int*、const int * const 和 int const * 之间有什么区别? - What is the difference between const int*, const int * const, and int const *? `constexpr` 和 `const` 之间的区别 - Difference between `constexpr` and `const`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM