Re: 'auto' keyword
On 3/12/23 06:07, DLearner wrote: > 1. As a shorthand to make the type of the variable being declared the > same as the type on the right hand side of an initial assignment. As Adam explained, D already has type inference without a special keyword. However, some places where 'auto' (or 'const', etc.) appear is not only for "shorthand" but for necessity. Some types cannot be spelled-out at all: auto foo() { struct S {} return S(); } void main() { pragma(msg, typeof(foo())); auto s = foo(); } The name 'S' is available only inside 'foo', so code outside has no choice but to use 'auto' (or 'const', etc.) Having said that, it is still possible to alias the returned type, which may be cumbersome in some cases because you may have to come up with a clean expression for attempting to call the function. In this case it's trivial because foo does not take any parameter: alias T = typeof(foo()); T t;// <-- There: I did not need to use 'auto' Ali
Re: 'auto' keyword
On Sunday, 12 March 2023 at 13:27:05 UTC, Adam D Ruppe wrote: [...] *any* storage class will work for type inference. [...] After heaving read [1] I immediately thought of this: void main () { deprecated i = 3; i = 4; } $ dmd test.d test.d(4): Deprecation: variable `test.main.i` is deprecated Does that make sense??? [1] https://issues.dlang.org/show_bug.cgi?id=7432 Issue 7432 - DMD allows variables to be declared as pure
Re: 'auto' keyword
On Sunday, 12 March 2023 at 15:31:07 UTC, Salih Dincer wrote: Moreover, `auto ref` or `ref auto` is needed in functions. That's because `ref` isn't part of the argument or return value's type, so it isn't covered by **type** inference. Instead, D has a totally separate feature for "`ref` inference".
Re: 'auto' keyword
On Sunday, 12 March 2023 at 13:07:58 UTC, DLearner wrote: Is it correct that this _single_ keyword is used to indicate _two_ quite different things: 1. As a shorthand to make the type of the variable being declared the same as the type on the right hand side of an initial assignment. The auto keyword is really helpful for shortening it. But in at least 2 cases (one of which is interfaces) it should help the compiler. For example, contrary to expected, it is dynamic array: ```d auto arr = [ 1, 2, 3 ]; ``` Moreover, `auto ref` or `ref auto` is needed in functions. SDB@79
Re: 'auto' keyword
On Sunday, 12 March 2023 at 13:07:58 UTC, DLearner wrote: Is it correct that this _single_ keyword is used to indicate _two_ quite different things: No, it only actually does #2 in your thing. The type is optional meaning *any* storage class will work for type inference. `auto` is not special in variable declarations. (it can be special in other contexts though). auto A = 5; static A = 5; const A = 5; all the same.
'auto' keyword
Is it correct that this _single_ keyword is used to indicate _two_ quite different things: 1. As a shorthand to make the type of the variable being declared the same as the type on the right hand side of an initial assignment. Example: ```auto A = 5;``` makes A an int. 2. To indicate storage class of variable. Example: ```auto int A;``` (I guess) makes A have automatic storage, ie contents lost when control goes out of scope, unlike static. Best regards
Re: auto keyword
On Thu, Jan 30, 2020 at 09:37:40AM +, Michael via Digitalmars-d-learn wrote: [...] > auto elements = buf.to!string.strip.split(" ").filter!(a => a != ""); > > That line strips white space from buf, splits it, removes empty > elements and returns an array of strings. At least I thought so. If you want an array of strings, just add .array to the end, and you will get string[] back. > Indeed elements can be treated as a string slice, but if i replace > auto by string[] the compiler complains: > Error: cannot implicitly convert expression filter(split(strip(to(buf)), " > ")) of type FilterResult!(__lambda1, string[]) to string[] That's because the actual type is a lazily-evaluated range. > In order to use an explicit type I wonder what kind of type I might > use instead of auto? In this case, you actually can't spell out the type, because it's a Voldemort type (it's only defined inside the function that constructs it, and is not directly nameable outside). Usually, a Voldemort type is returned when you *shouldn't* be referring to it with an explicit type. For example, in this case, if what you really want is an array of strings then you should add .array at the end to get a string[]. If you wish to store the lazy range, for whatever reason, you can use the typeof() operator to extract a type from it (without actually spelling it out -- because you can't): auto elements = buf.to!string.strip.split(" ").filter!(a => a != ""); alias E = typeof(elements); E x; x = elements; Usually this is only useful if you wish the store the lazy range inside some kind of aggregate type while retaining its lazy evaluation semantics. But if you expect it to be eagerly evaluated anyway, there's no need to jump through hoops to get at the type of `elements`; just stick .array to the end of it and get a string[] back. T -- "The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts." -- Bertrand Russell. "How come he didn't put 'I think' at the end of it?" -- Anonymous
Re: auto keyword
On Thursday, January 30, 2020 2:37:40 AM MST Michael via Digitalmars-d-learn wrote: > auto is surely a nice feature. Nonetheless I'd prefer to use > explicit types. So when reading a code and I see the auto keyword > I also have to find out what kind of type is meant. > > I have a line of code that looks like this: > auto elements = buf.to!string.strip.split(" ").filter!(a => a != > ""); > > That line strips white space from buf, splits it, removes empty > elements and returns an array of strings. At least I thought so. > > Indeed elements can be treated as a string slice, but if i > replace auto by string[] the compiler complains: > Error: cannot implicitly convert expression > filter(split(strip(to(buf)), " ")) of type > FilterResult!(__lambda1, string[]) to string[] > > In order to use an explicit type I wonder what kind of type I > might use instead of auto? For code like that, you don't. A lot of code in D - especially code that uses ranges - uses what are called Voldemort types. They are declared inside the function and you have no access to them. They follow a known API, so you know what to do with them, but you they have no name that you have access to. Realistically though, even if you had access to the type's name, you wouldn't want to use it explicitly anyway, because usually, it's a templated type which is instantiated with another templated type and is likely several layers deep. Using the explicit names would be hideous. Years ago (before we had Voldemort types), there was a bug in ddoc that made functions that returned auto not show up in the documentation. So, all of std.algorithm returned explicit types, and they were so hideous that it just scared people. It works _far_ better to just understand how to use these types and not use their names explicitly. It also makes the code far more resilient to changes, since as long as the return type retains the same API, it doesn't matter how the return type is changed. A function like filter could have its return type changed to something else, and the code calling it wouldn't care so long as it was the same kind of range. Since you probably aren't familiar with ranges in D (or you wouldn't be trying to use them by name), I suggest that you read this: http://ddili.org/ders/d.en/ranges.html And in addition to the fact that you pretty much have to use auto with range-based code, you're pretty much going to have to get used to dealing with D code using auto heavily, because that's what most D code does. Certainly, sometimes, you can use type names explicitly, but it's common practice to use auto most of the time. It can take a bit of getting used to, but ultimately, it actually results in more maintainable code. - Jonathan M Davis
auto keyword
auto is surely a nice feature. Nonetheless I'd prefer to use explicit types. So when reading a code and I see the auto keyword I also have to find out what kind of type is meant. I have a line of code that looks like this: auto elements = buf.to!string.strip.split(" ").filter!(a => a != ""); That line strips white space from buf, splits it, removes empty elements and returns an array of strings. At least I thought so. Indeed elements can be treated as a string slice, but if i replace auto by string[] the compiler complains: Error: cannot implicitly convert expression filter(split(strip(to(buf)), " ")) of type FilterResult!(__lambda1, string[]) to string[] In order to use an explicit type I wonder what kind of type I might use instead of auto?
Re: Auto keyword and when to use it
On Tuesday, 21 August 2018 at 21:37:00 UTC, QueenSvetlana wrote: I had a misunderstanding about the keyword auto because I wrongfully believed that it made the code like Python Exactly, you are thinking still like D is Python or also dynamically typed. :) You will get when compiling errors that Python wouldn't detect until run-time (or with your private methods). - A declaration with auto needs to include an initialization. - The code will be equivalent as if replacing "auto" with the inferred type. It is not left for later to check. I'm not terribly bothered btw by "Type = new Type()" but often type names get too long or include namespaces... "mylib.numeric.squareObjectWithPointyCorners = new mylib.numeric.squareObjectWithPointyCorners()"
Re: Auto keyword and when to use it
On Tuesday, 21 August 2018 at 18:44:15 UTC, Jim Balter wrote: Python is not statically typed; D is. Why are you talking about Python? You asked whether D's auto is like C#'s var ... it is, but it doesn't have C#'s pointless restriction of not being allowed for non-local declarations. I think you misunderstood my point. Let me elaborate. In Python a type could change at anytime, for example: number = 1 In Python the variable number will be treated as an int, but at any point in my code, that could change, in Python this is legal: number = "one" The code will compile and run. Now Python introduced type hints to tell the reader how to treat the variable. The problem with the code is, when you have a class, take my Person example, a person will obviously have a first and last name, which should be strings, now without validation I can pass ints to those variables, which is undesirable. I would need a private function to check the types passed and reject it if they aren't strings, in addition to if the string is blank or contains foreign characters. I had a misunderstanding about the keyword auto because I wrongfully believed that it made the code like Python, and for that I apologize. I thought you were allowed to make class variables auto, so for example: class Person{ auto firstName auto lastName } If this was allowed, when I create my person object, I can pass ints to firstName and lastName, which is obviously undesirable. I would need to check what value types were passed and reject them if they aren't strings. As pointed out in the answers above, this isn't legal, which means, there is no need to check anything, it won't compile.
Re: Auto keyword and when to use it
On Tuesday, August 21, 2018 12:22:42 PM MDT QueenSvetlana via Digitalmars-d- learn wrote: > On Monday, 20 August 2018 at 17:55:11 UTC, JN wrote: > > class Foo > > { > > > > auto bar; > > > > } > > > > because now the compiler doesn't know what type 'bar' is > > supposed to be. > > Just to clarify, even if I set bar in the constructor, I can't > declare it with auto first, correct? I would have to declare a > specific type? Yes. As Mike's excellent response explained, auto is simply used to indicate that you're not providing the explicit type and that it should be inferred from the direct initialization of the variable. Whenever an explicit type is not provided for a variable when declaring it, you _must_ use direct initialization so that the type can be inferred. You can't do something like have the type of a member variable inferred from what the constructor is doing. And code like auto foo; is never legal. - Jonathan M Davis
Re: Auto keyword and when to use it
On Tuesday, August 21, 2018 9:04:31 AM MDT Steven Schveighoffer via Digitalmars-d-learn wrote: > On 8/20/18 9:15 PM, Mike Parker wrote: > > I tend to use type inference liberally, almost always with > > const/immutbale locals, though I tend to use auto only when the type > > name is longer than four characters. For me, it's a nice way to save > > keystrokes. Some take a dim view of that approach and prefer to use it > > only when they actually require type inference. I mostly program alone, > > though, and I have a number of habits others may label 'bad', so I'm > > happy with my approach. > > I'm more extreme in this camp -- I use auto everywhere. Why? because at > some point, I may change some type somewhere (oops, I should have wrote > size_t instead of uint), and then I would have to go through and change > all the places I put the concrete type if I hadn't used auto. > > While using functions, I also can use auto and not have to worry about > the type. I know kind of what it is (integer type, string type, range > type, etc), and not care what the exact type is. I'd argue that it's generally better to use explicit types where possible in function signatures so that the documentation is clearer, but overall, I agree with you, and if I can use type inference, I almost always do. However, it does seem like the sort of thing that many newcomers to D balk at initially, whereas most of us who have been using it for a while have no problem with it and prefer it. - Jonathan M Davis
Re: Auto keyword and when to use it
On Tuesday, 21 August 2018 at 18:18:25 UTC, QueenSvetlana wrote: On Tuesday, 21 August 2018 at 16:15:32 UTC, XavierAP wrote: Only if someone likes "Type x = new Type()" instead of "auto x = new Type()" I would say they're clearly wrong. As you stated it's up to the programmer to decided. I'm in favor of Type x = new Type() There is nothing to recommend such redundancy; don't do it. because when it comes to constructing a class it usually means more code to verify the types Type inference doesn't require more code. for example: Your example has no bearing on any of the above ... it's not an example of it. class Person { auto firstName; auto lastName; // constuctor to set first and last names } That code is meaningless and isn't legal. You need to either provide explicit types, or they need to be inferable from the type of the initializer. The compiler doesn't know know what firstName or lastName is supposed to be and a programmer might make the obvious assumption and use them as strings. The programmer can't make any assumption because the code is not remotely legal. Doing this also means you have reject any type that isn't a string which means a private function to check the type that was pass to the constructor before initializing it. Where as if you declared it as a string to start of with, all you have to ensure is that it's not blank or contain illegal characters. This is all incoherent. D is a statically typed language. As the answer stated above doing what I showed in my example isn't allowed and this is where Python gets frustrating, because at any point the types could change. They introduced type hints, but it's not enforced, it just makes it more readable, you still have to write code to ensure the proper types were passed. Python is not statically typed; D is. Why are you talking about Python? You asked whether D's auto is like C#'s var ... it is, but it doesn't have C#'s pointless restriction of not being allowed for non-local declarations.
Re: Auto keyword and when to use it
On Monday, 20 August 2018 at 17:55:11 UTC, JN wrote: class Foo { auto bar; } because now the compiler doesn't know what type 'bar' is supposed to be. Just to clarify, even if I set bar in the constructor, I can't declare it with auto first, correct? I would have to declare a specific type?
Re: Auto keyword and when to use it
On Tuesday, 21 August 2018 at 16:15:32 UTC, XavierAP wrote: Only if someone likes "Type x = new Type()" instead of "auto x = new Type()" I would say they're clearly wrong. As you stated it's up to the programmer to decided. I'm in favor of Type x = new Type() because when it comes to constructing a class it usually means more code to verify the types, for example: class Person { auto firstName; auto lastName; // constuctor to set first and last names } The compiler doesn't know know what firstName or lastName is supposed to be and a programmer might make the obvious assumption and use them as strings. Doing this also means you have reject any type that isn't a string which means a private function to check the type that was pass to the constructor before initializing it. Where as if you declared it as a string to start of with, all you have to ensure is that it's not blank or contain illegal characters. As the answer stated above doing what I showed in my example isn't allowed and this is where Python gets frustrating, because at any point the types could change. They introduced type hints, but it's not enforced, it just makes it more readable, you still have to write code to ensure the proper types were passed.
Re: Auto keyword and when to use it
On Monday, 20 August 2018 at 17:52:17 UTC, QueenSvetlana wrote: So I can't declare class level variables with auto, correct? only local method variables? One difference between D's auto and C#'s var or C++'s auto is that the latter languages allow automatically typed declarations only for local (method/function-scope) variables, and forbid them for class or struct member variables (aka fields); whereas D allows auto anywhere (even function/method return type! -- which C# and C++ allow as well but only case of anonymous methods/lambdas). I'm in favor of the AAA ("Auto" Almost Always) paradigm, but as long as the type if obvious to a human reader. I don't favor them for numeric types for this reason (non obvious bitsize, signedness...) It's up to each programmer. Only if someone likes "Type x = new Type()" instead of "auto x = new Type()" I would say they're clearly wrong.
Re: Auto keyword and when to use it
On 8/20/18 9:15 PM, Mike Parker wrote: I tend to use type inference liberally, almost always with const/immutbale locals, though I tend to use auto only when the type name is longer than four characters. For me, it's a nice way to save keystrokes. Some take a dim view of that approach and prefer to use it only when they actually require type inference. I mostly program alone, though, and I have a number of habits others may label 'bad', so I'm happy with my approach. I'm more extreme in this camp -- I use auto everywhere. Why? because at some point, I may change some type somewhere (oops, I should have wrote size_t instead of uint), and then I would have to go through and change all the places I put the concrete type if I hadn't used auto. While using functions, I also can use auto and not have to worry about the type. I know kind of what it is (integer type, string type, range type, etc), and not care what the exact type is. -Steve
Re: Auto keyword and when to use it
On Monday, 20 August 2018 at 17:24:19 UTC, QueenSvetlana wrote: I'm struggling to understand what the auto keyword is for and it's appropriate uses. From research, it seems to share the same capabilities as the var keyword in C#. auto is one of the most misunderstood understood features in D. By that I mean, everyone understands the effect of auto, but aren't always accurate in describing it. In D, every variable must have a storage class. The automatic storage class is the default and is never specified in the declaration: int x = 10; Other storage classes are const, immutable, and shared. These are also type constructors, so they become part of the type: const int y = 11; // type is const(int) immutable int z = 12; // type is immutable(int) shared int s = 13; // type is shared(int) D allows the type to be dropped in declarations that include an initializer. In those cases, the type will be inferred: const y = 11; // type is const(int) immutable z = 12; // type is immutable(int) shared s = 13; // type is shared(int) You can also drop the type in declarations with automatic storage, but `x = 10;` is not allowed as a variable declaration. You must include at minimum a type or a storage class. That's where auto comes in: auto x = 10; // type is int So that's all it is. It's nothing special. It just means you're declaring a variable with the default storage class and want the compiler to infer the type. So the question 'when should I use auto' is probably the wrong way to look at it. 'When should I use type inference' is a better way to frame it. And the answer to that is that there is no right answer. I tend to use type inference liberally, almost always with const/immutbale locals, though I tend to use auto only when the type name is longer than four characters. For me, it's a nice way to save keystrokes. Some take a dim view of that approach and prefer to use it only when they actually require type inference. I mostly program alone, though, and I have a number of habits others may label 'bad', so I'm happy with my approach.
Re: Auto keyword and when to use it
On Monday, 20 August 2018 at 17:52:17 UTC, QueenSvetlana wrote: Great! So I can't declare class level variables with auto, correct? only local method variables? You can, globals, class members: class Foo { auto bar = "hi"; } Foo.bar will be of string type here, because "hi" is a string. What you can't do is: class Foo { auto bar; } because now the compiler doesn't know what type 'bar' is supposed to be.
Re: Auto keyword and when to use it
On Monday, 20 August 2018 at 17:52:17 UTC, QueenSvetlana wrote: Great! So I can't declare class level variables with auto, correct? only local method variables? You can use auto if you're setting the class level variable to a default. class X { auto i = 42; // i will be an int }
Re: Auto keyword and when to use it
Great! So I can't declare class level variables with auto, correct? only local method variables?
Re: Auto keyword and when to use it
On Monday, 20 August 2018 at 17:24:19 UTC, QueenSvetlana wrote: I'm new to D programming, but have I have a background with Python. I'm struggling to understand what the auto keyword is for and it's appropriate uses. From research, it seems to share the same capabilities as the var keyword in C#. From the C# documentation, it states: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var ... variables that are declared at method scope can have an implicit "type" var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. Is the same true for auto? For example, if I have a class Person, I might have attributes such as FirstName, LastName which should obviously be strings but will D allow me to declare class level attributes with auto? C# doesn't allow this. It basically works like C#. auto x = "hi"; will make x a string. But if you later try: x = 5; it will throw an error, because x is a string. It's used to save you the typing of the type, it doesn't make the language dynamically typed.
Auto keyword and when to use it
I'm new to D programming, but have I have a background with Python. I'm struggling to understand what the auto keyword is for and it's appropriate uses. From research, it seems to share the same capabilities as the var keyword in C#. From the C# documentation, it states: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var ... variables that are declared at method scope can have an implicit "type" var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. Is the same true for auto? For example, if I have a class Person, I might have attributes such as FirstName, LastName which should obviously be strings but will D allow me to declare class level attributes with auto? C# doesn't allow this.
Re: Auto keyword with const variable
On Wednesday, 24 July 2013 at 11:26:32 UTC, Mike Parker wrote: This is the exact behavior I would expect. I think of auto as this variable is going to be the same type as that variable. Since in is const int, then j also is going to be const int. If you want to copy n into a nonconst variable, you have to cast away the const. int j = cast( int )n; auto j = cast( int )n; Casting is always an extreme measure, one that should be avoided in mundane code as much as possible. Despite the fact `auto` behaves as it should, this really highlights lack of `mutable` attribute in language.
Auto keyword with const variable
This code: void test(const int n) { auto j = n; j++; } Gives this error: cannot modify const expression j Is this considered a feature or a bug? I would assume most people wouldn't want new variables inheriting const.
Re: Auto keyword with const variable
Alex H: void test(const int n) { auto j = n; j++; } Gives this error: cannot modify const expression j Is this considered a feature or a bug? I would assume most people wouldn't want new variables inheriting const. It's a bit annoying. I don't remember people discussing this small problem. I don't know if it's easy to fix it and what side effects such change could cause. Bye, bearophile
Re: Auto keyword with const variable
On Wednesday, 24 July 2013 at 08:07:55 UTC, Alex H wrote: This code: void test(const int n) { auto j = n; j++; } Gives this error: cannot modify const expression j Is this considered a feature or a bug? I would assume most people wouldn't want new variables inheriting const. There is no error. All right. auto - the type expects the maximum transfer of properties from the context. int j = n; j++ // if change j
Re: Auto keyword with const variable
Am 24.07.2013 11:39, schrieb bearophile: Alex H: void test(const int n) { auto j = n; j++; } Gives this error: cannot modify const expression j Is this considered a feature or a bug? I would assume most people wouldn't want new variables inheriting const. It's a bit annoying. I don't remember people discussing this small problem. I don't know if it's easy to fix it and what side effects such change could cause. should that be fixed - i don't think that any auto removal of const, immutable, shared or anything else should just happen silently and how would it look to preserve the const if auto would auto-rip it of?
Re: Auto keyword with const variable
dennis luehring: and how would it look to preserve the const if auto would auto-rip it of? You could write: immutable j = n; For every default behavour you need a way to implement the other nicely :-) Currently for the problem of the OP you can use this: Unqual!(typeof(n)) j = n; Bye, bearophile
Re: Auto keyword with const variable
On Wednesday, 24 July 2013 at 10:01:14 UTC, bearophile wrote: dennis luehring: and how would it look to preserve the const if auto would auto-rip it of? You could write: immutable j = n; For every default behavour you need a way to implement the other nicely :-) Currently for the problem of the OP you can use this: Unqual!(typeof(n)) j = n; Bye, bearophile Definitly. Auto means same type. I think it could be OK if it followed IFTI rules? After all, in concept, it's kind of the same mechanism. I wouldn't go any further than that though. // void foo(T)(T t) { pragma(msg, T.stringof); } void main(string[] args) { immutable int[] i = [1, 2, 3]; foo(i); auto j = i; pragma(msg, typeof(j).stringof); } // immutable(int)[] immutable(int[]) // Problem: I don't really see a good usecase for making auto have special IFTI behavior. Keeping it to same type, 100% of the time seems like the best.
Re: Auto keyword with const variable
On 07/24/13 12:09, monarch_dodra wrote: Keeping it to same type, 100% of the time seems like the best. No, it's a design bug. The head qualifier(s) should always be stripped when copying objects. Stripping is always fine (ie safe), not doing it just creates other problems, like the one in OP, or unnecessary template bloat. The IFTI special cases that are already there are just handling one of the symptoms. As you can always declare something as 'immutable' or 'const', instead of 'auto', the default would have to be head-mutable [1]. Ie, this would then work: const int a; immutable b = a; // immutable int const c = a; // const int auto d = a; // int Right now, you have to do `auto d = cast()a;` or use the Unqual hack... artur [1] If D had a `var` qualifier, then defaulting to 'const' might be better. But it doesn't.
Re: Auto keyword with const variable
On Wednesday, 24 July 2013 at 10:37:40 UTC, Artur Skawina wrote: On 07/24/13 12:09, monarch_dodra wrote: Keeping it to same type, 100% of the time seems like the best. No, it's a design bug. The head qualifier(s) should always be stripped when copying objects. Stripping is always fine (ie safe) Nope. Stop. Wrong. Qualification is transitive in D, unlike in C++. Even when copying, stripping qualification is not safe: // struct S { int* p; } void main() { immutable i = 1; auto a = immutable(S)(i); auto b = cast(S)a; //Unsafe cast *b.p = 2; //This'll probably crash on a linux //Program corrupted by here. assert(i == *i); //This fails (!!!) on my win32 } // Long story short, never cast to Unqual. Always to an implicit cast, and let the compiler complain if it is illegal: // struct S1 { int a; } struct S2 { int* p; } void main() { immutable i = 1; auto a1 = immutable(S1)(i); auto a2 = immutable(S2)(i); S1 b1 = a1; //OK! S2 b2 = a2; //Error: cannot implicitly convert expression (a2) of type immutable(S2) to S2 } //
Re: Auto keyword with const variable
On Wednesday, 24 July 2013 at 08:07:55 UTC, Alex H wrote: This code: void test(const int n) { auto j = n; j++; } Gives this error: cannot modify const expression j Is this considered a feature or a bug? I would assume most people wouldn't want new variables inheriting const. This is the exact behavior I would expect. I think of auto as this variable is going to be the same type as that variable. Since in is const int, then j also is going to be const int. If you want to copy n into a nonconst variable, you have to cast away the const. int j = cast( int )n; auto j = cast( int )n;
Re: Auto keyword with const variable
On Wednesday, July 24, 2013 10:07:54 Alex H wrote: This code: void test(const int n) { auto j = n; j++; } Gives this error: cannot modify const expression j Is this considered a feature or a bug? I would assume most people wouldn't want new variables inheriting const. The behavior is correct and desirable. It would be a big problem for generic code if the type of auto didn't match the right-hand side of the expression. In some cases, it might be okay if auto gave you the tail-const type, but even that could be problematic depending on the type. - Jonathan M Davis
Re: Auto keyword with const variable
On Wednesday, 24 July 2013 at 11:26:32 UTC, Mike Parker wrote: ... This is the exact behavior I would expect. I think of auto as this variable is going to be the same type as that variable. Since in is const int, then j also is going to be const int. If you want to copy n into a nonconst variable, you have to cast away the const. int j = cast( int )n; auto j = cast( int )n; +1 This works fine for pods, no cast required int j = n; ++j; ...and this does what one would expect too struct S { int* value; } void funky(const S s) { int* s1 = s.value; *s1 = 5; } /d535/f466.d(9): Error: cannot implicitly convert expression (s.value) of type const(int*) to int* void funky(const S s) { S s1 = s; *s1.value = 5; } /d297/f947.d(9): Error: cannot implicitly convert expression (s) of type const(S) to S
Variable declaration programming style and the auto keyword
I've seen a lot of code lately that uses the auto keyword when declaring variables, but for some reason I don't really care much for it. I'd like to make tutorials for a library I am working on, but I want to use D style. Does such a style exist? Is auto generally preferred when declaring variables? How often does everyone here use it? Thanks much! Jeremy
Re: Variable declaration programming style and the auto keyword
On Thursday, 4 July 2013 at 20:00:18 UTC, Jeremy DeHaan wrote: I've seen a lot of code lately that uses the auto keyword when declaring variables, but for some reason I don't really care much for it. I'd like to make tutorials for a library I am working on, but I want to use D style. Does such a style exist? Is auto generally preferred when declaring variables? How often does everyone here use it? Thanks much! Jeremy I only use it if I have a long or ugly name, like shared_ptr!(SomeType, SomeDeallocatorFunc) share = shared_ptr!(SomeType, SomeDeallocatorFunc)(new A(42)); Then I would write: auto share = shared_ptr!(SomeType, SomeDeallocatorFunc)(new A(42)); because it is clear what share is and what type it should have.
Re: Variable declaration programming style and the auto keyword
On Thursday, July 04, 2013 21:54:22 Jeremy DeHaan wrote: I've seen a lot of code lately that uses the auto keyword when declaring variables, but for some reason I don't really care much for it. I'd like to make tutorials for a library I am working on, but I want to use D style. Does such a style exist? Is auto generally preferred when declaring variables? How often does everyone here use it? There's some debate as to how much to use auto, but at absolute minimum, it should be used it situations where 1. Using it would just unnecessarily duplicate the type, like in int i = cast(int)foo; MyClass c = new MyClass; int[] arr = new int[](5); Those definitely should be auto i = cast(int)foo; auto c= new MyClass; auto arr = new int[](5); 2. Where giving the exact type would be tedious. For instance, with std.algorithm.until. You could write Until!(a == b, int[], int) result = [1, 2, 3, 4, 5].until(3); or you could write auto result = [1, 2, 3, 4, 5].until(3); 3. When you need to infer the type. This is frequently the case in generic programming, as the type could change depending on what was passed to a templated function, and with Voldemort types (return types which are declared internally to a function, so you don't have access to their name), you _have_ to use auto. This is frequently done with range-based algorithms, as the type doesn't matter, just the API. So, at _absolute minimum, auto should be used in those circumances. However, many of us would argue that auto should almost always be used unless you actually need to give an explicit type. And a _lot_ of D code is written this way. By using auto heavily, refactoring code becomes _much_ easier, because you don't have to go and change the type of your variables all over the place when you make changes. If you need the type to be explicit, then you have to make it explicit. For instance, auto i = 7; will result in i being an int when maybe you need to be be size_t. In such cases, you'd have to explicitly give the type. size_t i = 7; And of course, there are times when using an explicit type improves clarity, so there's some art to choosing when to use auto and when not to, but for the most part, code is more maintainable when you don't use explicit types when you don't actually need to. - Jonathan M Davis