What happens if undefined C++ behaviour meets C defined behaviour?

Viewed 901

I have a *.cpp file that I compile with C++ (not a C compiler). The containing function relies on a cast (see last line) which seems to be defined in C (please correct if I am wrong!), but not in C++ for this special type.

[...] C++ code [...]

struct sockaddr_in sa = {0};
int sockfd = ...;
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
bind(sockfd, (struct sockaddr *)&sa, sizeof sa);

[...] C++ code [...]

Since I compile this in a C++ file, is this now defined or undefined behaviour? Or would I need to move this into a *.c file, to make it defined behaviour?

2 Answers

This is defined in both C++ and C. It does not violate strict aliasing regulations as it does not dereference the resulting pointer.

Here's the quote from C++ (thanks to @interjay and @VTT) that allows this:

An object pointer can be explicitly converted to an object pointer of a different type.

Here's the quote from C (thanks @StoryTeller) that allows this:

A pointer to an object type may be converted to a pointer to a different object type.

These specify that one pointer type can be converted to another pointer type (and then optionally converted back) without consequence.

And here's the quote from POSIX that allows this specific case:

The sockaddr_in structure is used to store addresses for the Internet address family. Pointers to this type shall be cast by applications to struct sockaddr * for use with socket functions.

As this function (bind) is part of the C standard library, whatever goes on inside (specifically, dereferencing the type-casted pointer) does not have undefined behavior.


To answer the more general question:

C and C++ are two different languages. If something is defined in C but not in C++, it's defined in C but not in C++. No implied compatibility between the two languages will change that. If you want to use code that is well-defined in C but is undefined in C++, you'll have to use a C compiler to compile that code.

Calls between C and C++ code all invoke Undefined Behavior, from the point of view of the respective standards, but most platforms specify such things.

In situations where parts of the C or C++ Standard and an implementation's documentation together define or describe an action, but other parts characterize it as Undefined, implementations are allowed to process code in whatever fashion would best serve their customers' needs or--if they are indifferent to customer needs--whatever fashion they see fit. The fact that the Standard regards such matters as outside their jurisdiction does not imply any judgment as to when and/or how implementations claiming suitability for various purposes should be expected to process them meaningfully, but some compiler maintainers subscribe to a myth that it does.

Related