DEV Community

Cover image for Type Safety in C++
Saloni Goyal
Saloni Goyal

Posted on • Edited on

7 3

Type Safety in C++

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

Alt Text

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (3)

Collapse
 
sandordargo profile image
Sandor Dargo

The compiler might or might not warn you if you demote or narrow variables.

Try this:

#include <iostream>

int main() {
  unsigned int i = -5;
  short x = (short)0x12345678L;
  std::cout << i << std::endl;
  std::cout << x << std::endl;
}
Enter fullscreen mode Exit fullscreen mode

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.

#include <iostream>

int main() {
  unsigned int i {-5};
  std::cout << i << std::endl;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
blender profile image
Saloni Goyal

Yes 🤩, the first method didn't give any warning. The second one gave a compiler error on Xcode.
error

Collapse
 
blender profile image
Saloni Goyal

Thank-you so much everyone.
thank-you

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay