5 ms·
> C++ has already adopted type inference, where the compiler figures out what the appropriate type for the variable should be from how it is used, in this case.
by tjoff 3y ago
> C++ has already adopted type inference, where the compiler figures out what the appropriate type for the variable should be from how it is used, in this case. There are schemes afoot to add a similar feature to C, but type inference is incompatible with implicit int.
Please no. In C++ this only makes sense when you have huge templated types such as iterators etc. Or inside templates where the types are not fixed.
Neither exist in C. It is just a distraction with no benefits in C.
- spacechild1 3y agoOr when the type is hidden (lambdas). Or to avoid needless redundandancy (e.g : auto foo = std::make_unique<Foo>()). And probably some more.
- kazinator 3y agoC has type generic math (which came first) and something called generic selection via _Generic (which came later, and provides a model for implementing the type generic math stuff). I suspect that a C++-like auto could be of benefit in conjunction with that stuff.
- pjmlp 3y agoIt is already there in C23.
- quelsolaar 3y agoAnd its broken! Consider: auto i = 0.0; i is a double in C23 but an int in earlier version. Please don't use C23.
- lionkor 3y ago0.0 is a double literal, how is that broken?
- quelsolaar 3y agoBecause it changes the meaning of existing code. That's a big no-no.
- JonChesterfield 3y agoMaybe people could grep for "auto" in their codebase, see it's not there, and then change to C23? Though realistically if this looks like a problem it's a trivial compiler diagnostic. "Would this thing have a different type in C23 to earlier? Emit a warning, promotable to error". The whole changes meaning panic is rather overdone and mostly acts to stop C improving over time.
- actionfromafar 3y agoChesters' (green) field, where Chesterton's fence is. :)
- quelsolaar 3y agoYou cant make a compiler diagnostic, because it was valid before and after C23, the code just means different things. In fact just using auto without a type was bad practice in earlier versions, now it can be considered a feature, so its less likely to give you a warning now than in the past.
- ahartmetz 3y agoThere is the "Almost Always Auto" idea in C++, but AFAICS it's (fortunately IMO) not catching on.
- eska 3y agoI can think of many counter examples, e.g auto v = MAX(a, b); where max infers the result type from the input types using generics or compiler intrinsics. auto v = (struct foo){.a = 1}; where one wouldn’t want to repeat the type as in C++ auto v = make_unique<foo>(1);
- cozzyd 3y agoan auto cast based on the destination type might be cleaner, a la struct foo v = (auto) {.a = 1 };