Confusion regarding char[] [duplicate] - c++

This question already has an answer here:
Should statically-declared character arrays with a specified size be initialized with a literal in C?
(1 answer)
Closed 8 years ago.
I have recently started programming in C++ and that's why I am facing lots of confusions.
I wanted to know what's wrong in using the following piece of code:
char interface[20];
interface="USB01";

The C++ language does not allow you to assign to arrays.
You can, however, initialize arrays. The syntax is similar, but the assignment operator is used in the same statement as the declaration:
char interface[20] = "USB01";
However, in C++, one would typically use a standard container like std::string rather than C strings. These are far easier to use and do allow for natural assignments.
std::string interface;
....
interface = "USB01";
Note that we don't need to decide up front how much space to reserve for the string. This is just one of the many benefits of using the standard string class.

You can't assign arrays like that, but you can initialise them:
char interface[20] = "USB01";
In C++ though you should be using proper C++ strings, i.e. std::string, not C-style char * strings:
std::string interface;
interface = "USB01";

Related

Changing/punning types [duplicate]

This question already has answers here:
C++ cast syntax styles
(10 answers)
What's the difference between type(myVar) and (type)myVar?
(2 answers)
What is the difference between (type)value and type(value)?
(5 answers)
Closed 3 years ago.
Consider:
b = (int) a; // C-like cast notation
b = int (a); // Functional notation
Apparently I was wrong in my initial cut at an answer. They are roughly equivalent. And while compound type names like long long or void * can't use functional syntax directly (i.e. long long(val) doesn't work), using typedef can get around this issue.
Both cast notations are very bad and should be avoided. For example:
const char c = 'a';
void *fred = (void *)(&c);
works, and it shouldn't.
Both the C-style cast notation will sometimes behave like static_cast, sometimes like const_cast, sometimes like reinterpret_cast, or even a combination of the two depending on the exact situation in which it's used. These semantics are rather complex and it's not always easy to tell exactly what's happening in any given situation.
I have gone to using mostly C++ static_cast<type>(val) style casts, and never use C-style casts. Based on my research for this question I'm going to also stop using function-style casts for anything. The question "C++ cast syntax styles" has an excellent answer (the accepted one) that details why.
There's hardly any difference. Officially, the first tells the compiler that the value is an integer. This probably doesn't generate any extra code at all. The function call is an actual call that internally performs the other typecast. A smart compiler will optimize this, so they are actually the same.
There isn't any difference. It is a matter of preference. These are old-style casts.
It depends where you use it and how. I.e. if you have values or pointers (or pointers of pointers).
With C++ you should read up on *_cast<> and use them instead.

Avoiding the func(char *) api on embedded

Note:
I heavily changed my question to be more specific, but I will keep the old question at end of the post, in case it is useful to anyone.
New Question
I am developing an embedded application which uses the following types to represent strings :
string literals(null terminated by default)
std::array<char,size> (not null terminated)
std::string_view
I would like to have a function that accepts all of them in a uniform way. The only problem is that if the input is a string literal I will have to count the size with strlen that in both other cases doesn't work but if I use size it will not work on case 1.
Should I use a variant like so: std::variant<const char *,std::span<char>> ? Would that be heavy by forcing myself to use std::visit ? Would that thing even match correctly all the different representations of strings?
Old Question
Disclaimer when I refer to "string" in the following context I don't mean an std::string but just an abstract way to say alphanumeric series.
Most of the cases when I have to deal with strings in c++ I use something like void func(const std::string &); or without the const and the reference at some cases.Now on an embedded app I don't have access to std::string and I tried to use std::string_view the problem is that std::string_view when constructed from a non literal sometimes is not null terminated
Edit: I changed the question a bit as the comments implied some very helphull hints .
So even though y has a size in the example below:
std::array<char,5> x{"aa"} ;
std::string_view y(x.data());
I can't use y with a c api like printf(%s,y.data()) that is based on null termination
#include <array>
#include <string_view>
#include "stdio.h"
int main(){
std::array<char,5> x{"aaa"};
std::string_view y(x.data());
printf("%s",x);
}
To summarize:
What can I do to implement a stack allocated string that implicitly gets a static size at its constructors (from null terminated strings,string literals, string_views and std::arrays) and it is movable (or cheap copyable)?
What would be the underlying type of my class? What would be the speed costs in comparison with the underlying type?
I think that you are looking at two largely and three subtly different semantics of char*.
Yes, all of them point at char but the type-specific info on how to determine the length is not carried by that. Even in the ancient ancestor of C++ (not saying C...) a pointer to char was not always the same. Already there pointers to terminated and non-terminated sequences of characters could not be mixed.
In C++ the tool of overloading a function exists and it seems to be the obvious solution for your problem. You can still implement that efficiently with only one (helper) function doing the actual work, based on an explicit size information in a second parameter.
Overload the function which is "visible" on the API, with three versions for the three types. Have it determine the length in the appropriate way, then call the single helper function, providing that length.

Returning primitive type arrays in C++ (Java comparison) [duplicate]

This question already has answers here:
Why doesn't C++ support functions returning arrays?
(10 answers)
Closed 4 years ago.
To clarify, my question is NOT the same as this one: How to return an array from a function?
The answers from that question basically say to return a pointer or use the array class.
In Java, you can return a primitive type array from a function (such as int[]). I want to know if you can return a primitive array WITHOUT using the array class.
EDIT:
I am expecting syntax like this:
int[] returnArrayFunc() { int a[2]; return a;}
EDIT #2:
I want to learn how to return arrays in C++, not Java.
Your question is a bit ambiguous, because you are asking a C question about Java. Java doesn't provide access to pointers. "a primitive array WITHOUT using the array class" isn't meaningful in Java.
BTW, you should ask this question on the C++ forum.
Edit:
This is an answer: In short, No.

C# extension methods analogue in C++ [duplicate]

This question already has answers here:
Extension methods in c++
(7 answers)
C++ Class Extension
(9 answers)
Closed 5 years ago.
C# has this little nice feature: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
This is really cool. Let me give you an example:
I want to add concat method to std::vector but I don't want to inherit it. This feature would be very useful. Do you have any analogues feature in C++ that allows to add a function to a type without inheriting from the original type? I am asking for a language-level feature, please.
In C++ this is not directly possible; that being said, you could implement a function that has a reference to a std::vector as a first argument, serving a similar purpose as an extension method (which more or less are just syntactic sugar for that).
A free function might be your friend here e.g.
namespace VectorMethods
{
std::string contat(const std::vector<std::string>& vec)
{
// return result of concatenating vector
}
}

C++ Classes - dot notation vs pointer [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the difference between the dot (.) operator and -> in C++?
What's the difference between using dot notation and the pointer way?
Instantiating an object with or without a pointer.
Instantiate w/o a pointer = then use dot notation
Instantiate w/ a pointer = then use ->
What are the differences between both? When and why should one be used over the other?
If I understand your question: in C++, a->b is just shorthand for (*a).b -- they're exactly the same (Edit: unless you've overloaded them to behave differently!), it's just that the first is easier to type. :)
If you're referring to using string a; versus string* a = new string(), that's a different topic -- look up stack-based and heap-based allocation.