C++ enforces types, that means, every variable has a type and then that is its type forever and it can't be changed.
Expressions like 2 or 2+2 also have a type.
It is okay to "promote"
- put an integer (eg 2) into a float
The compiler will however warn you if you "demote" and throw away information
- put a floating point number (say 4.9) into an integer
This applies for variables initialised using auto as well.
Some combinations are just not allowed and will result in compiler errors
- put a string into an int
- multiply a string and a float
Do try out the narrowing example shared by Sandor in the comments.
Please leave out comments with anything you don't understand or would like for me to improve upon.
Thanks for reading!
Top comments (3)
The compiler might or might not warn you if you demote or narrow variables.
Try this:
There is no compiler warning at all.
On the other hand, if you use a
{}
-initialization, you'll receive a compiler warning about a narrowing conversion.Yes 🤩, the first method didn't give any warning. The second one gave a compiler error on Xcode.
Thank-you so much everyone.