Why is processing a sorted array faster than processing an unsorted array?

Here is a piece of C++ code that shows some very peculiar behavior. For some strange reason, sorting the data (before the timed region) miraculously makes the loop almost six times faster. #include <algorithm> #include <ctime> #include <iostream> int main() { // Generate data const unsigned arraySize = 32768; int data[arraySize]; for (unsigned c = … Read more

System.out.println function syntax in C++

I want to create a function in C++ using cout that has the same as the println function in java. This means that the call should be something like this: [c]int a=5 println("A string" + a);[/c] the variable a should have any basic type. What kind of parameter should I have in this case and … Read more

How to static assert to disallow “mixed endianness” in a non-templated member function

I suggest asserting that it’s either big or little endian: [code]#include <bit> #include <compare> struct pawned_pw { std::strong_ordering operator<=>(const pawned_pw& rhs) const { static_assert(std::endian::native == std::endian::big || std::endian::native == std::endian::little, "mixed-endianess architectures are not supported"); if constexpr (std::endian::native == std::endian::little) { return …; } else { // big return …; } } };[/code]

Why is “while ( !feof (file) )” always wrong

What is wrong with using feof() to control a read loop? For example: [c]#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(int argc, char **argv) { char *path = "stdin"; FILE *fp = argc &gt; 1 ? fopen(path=argv[1], "r") : stdin; if( fp == NULL ){ perror(path); return EXIT_FAILURE; } while( !feof(fp) ){ /* THIS IS WRONG */ /* Read … Read more

Undefined, unspecified and implementation-defined behavior

What is undefined behavior (UB) in C and C++? What about unspecified behavior and implementation-defined behavior? and What is the difference between them? Best Answer Undefined behavior is one of those aspects of the C and C++ language that can be surprising to programmers coming from other languages (other languages try to hide it better). Basically, it is possible to write … Read more