Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is "char" a bad programming practice in struct types?

Tags:

c++

struct

I see in c++ programming language some recommendations like "don't use char in struct type",

struct Student{
    int stdnum, FieldCode, age;
    double average, marks, res[NumOfCourses];
    char Fname[20], Lname[20], cmp[20];
};

And is better to use:

struct Student{
    int stdnum, FieldCode, age;
    double average, marks, res[NumOfCourses];
    string Fname, Lname, cmp;
};

Any other recommendations would be welcome on the matter

Thank you in advance

like image 994
MLSC Avatar asked Aug 15 '26 11:08

MLSC


1 Answers

Because string handling using C-level raw character arrays is hard to get right, prone to fail, and when it fail it can fail rather horribly.

With a higher-level string datatype, your code becomes easier to write, more likely to be correct. It's also often easier to get shorter code, since the string datatype does a lot of work for you that you otherwise have to do yourself.

The original question was tagged with the c tag, but of course string is a c++ construct so this answer doesn't apply to C. In C, you can choose to use some string library (glib's GString is nice) to gain similar benefits but of course you'll never have overloaded operators like in C++.

like image 157
unwind Avatar answered Aug 17 '26 01:08

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!