简体   繁体   English

是否使用auto声明变量并使用原始文字定义的行为进行初始化?

[英]Is declaring a variable with auto and initializing with a primitive literal defined behaviour?

If I initialise a variable declared using auto with a primitive literal, are the results defined eg 如果我使用原始文字初始化使用auto声明的变量,则是否定义了结果,例如

auto i = 6; // Is this always going to evaluate to a int?
            // Or could it evaluate to some similar type like short?

The type of integer literal 6 is int , as you can check here . 整数文字6的类型为int ,您可以在此处检查。

Then, from the cppreference.com : 然后,从cppreference.com

For variables, auto specifies that the type of the variable that is being declared will be automatically deduced from its initializer. 对于变量, auto指定将从其初始值设定项自动推断出要声明的变量的类型。

So i will have type of int , because 6 has type of int . 所以i将具有int类型,因为6具有int类型。

And this behaviour is absolutely well-defined. 这种行为是绝对定义良好的。

Yes, that's exactly what auto is for. 是的,这正是auto的用途。

For example, auto i; 例如, auto i; wouldn't make sense. 没道理 The compiler uses 6 to deduce the type. 编译器使用6推断类型。 And 6 is an integer literal. 6是整数文字。

Yes, because every literal has a well defined type. 是的,因为每个文字都有明确定义的类型。 The type of literal 6 is int . 文字6的类型为int So, your auto will be translated to int . 因此,您的auto将被转换为int

If int is 16 or 32 bits long is implementation defined, but that's doesn't produce undefined behaviour, because every simple int through your program has a same length. 如果int是16或32位长,则定义实现,但这不会产生不确定的行为,因为程序中每个简单的int都具有相同的长度。 Besides that, irrespective of the length of a int according to your architecture, 6 is an int , not short or long . 除此之外,无论根据您的体系结构int的长度如何,6都是int ,而不是shortlong

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

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