Skip to main content
added 90 characters in body
Source Link
frozenca
  • 1.7k
  • 5
  • 20

Don't cast the result value of malloc(). (In general, using casts in C is a yellow card. Using C-style casts in C++ is a red card)

The reason to cast the result of malloc() is because C++ requires a cast for malloc(), but C doesn't require that.

  1. Using malloc() in C++ is already a red flag, so you don't need to cast the result of malloc()

  2. In C, casting the result of malloc() is actually very harmful.

If you forgot to include <stdlib.h> and you ignore compiler warnings, the result type of malloc() would be implicit int, so you will cast int to Queue*, god knows what will happen. This kind of bug is very hard to spot. If you don't cast, then implicit casting from int to Queue* is not allowed, so the compiler will reject your code for you.

Don't cast the result value of malloc().

The reason to cast the result of malloc() is because C++ requires a cast for malloc(), but C doesn't require that.

  1. Using malloc() in C++ is already a red flag, so you don't need to cast the result of malloc()

  2. In C, casting the result of malloc() is actually very harmful.

If you forgot to include <stdlib.h> and you ignore compiler warnings, the result type of malloc() would be implicit int, so you will cast int to Queue*, god knows what will happen. This kind of bug is very hard to spot. If you don't cast, then implicit casting from int to Queue* is not allowed, so the compiler will reject your code for you.

Don't cast the result value of malloc(). (In general, using casts in C is a yellow card. Using C-style casts in C++ is a red card)

The reason to cast the result of malloc() is because C++ requires a cast for malloc(), but C doesn't require that.

  1. Using malloc() in C++ is already a red flag, so you don't need to cast the result of malloc()

  2. In C, casting the result of malloc() is actually very harmful.

If you forgot to include <stdlib.h> and you ignore compiler warnings, the result type of malloc() would be implicit int, so you will cast int to Queue*, god knows what will happen. This kind of bug is very hard to spot. If you don't cast, then implicit casting from int to Queue* is not allowed, so the compiler will reject your code for you.

Source Link
frozenca
  • 1.7k
  • 5
  • 20

Don't cast the result value of malloc().

The reason to cast the result of malloc() is because C++ requires a cast for malloc(), but C doesn't require that.

  1. Using malloc() in C++ is already a red flag, so you don't need to cast the result of malloc()

  2. In C, casting the result of malloc() is actually very harmful.

If you forgot to include <stdlib.h> and you ignore compiler warnings, the result type of malloc() would be implicit int, so you will cast int to Queue*, god knows what will happen. This kind of bug is very hard to spot. If you don't cast, then implicit casting from int to Queue* is not allowed, so the compiler will reject your code for you.