Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

c++ - Explicit type conversion really necessary?

Arduino's LiquidCrystal Library defines

 virtual size_t write(uint8_t);

In their example you'll find a few calls to that function:

lcd.write(byte(0)); // when calling lcd.write() '0' must be cast as a byte
lcd.write((byte)1);
lcd.write(4);

My C++ is a bit rusty, so I'm not sure why they say it must be cast as a byte?

I mean you wouldn't do something like byte a = byte(0); right?

From what I remember and find in the C++ reference this type conversion should happen implicitly so there is no need to explicitly cast it in the function call.

Is this documentation/example just as inconsistent and bad as I think it is? Or am I missing something here?

question from:https://stackoverflow.com/questions/65883011/explicit-type-conversion-really-necessary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suspect that's due to these 2 overloads in the base class Print:

virtual size_t write(uint8_t);
size_t write(const char *str);

If called as write(0), the write(const char *) overload will be selected as a better candidate (the first requires a narrowing conversion, but 0 is a null-pointer).

So to send a 0 byte, you must use an explicit cast to help the compiler choose the right overload: write((uint8_t)0).


In addition, you can get a warning "narrowing conversion, possible loss of data" if you let a larger type implicitly convert to a smaller one. So it's always a good idea to use an explicit cast to tell the compiler you know what you're doing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...