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]

scanf() Leaves the Newline Character in the Buffer

I have the following program: [c]int main(int argc, char *argv[]) { int a, b; char c1, c2; printf("Enter something: "); scanf("%d",&a); // line 1 printf("Enter other something: "); scanf("%d", &b); // line 2 printf("Enter a char: "); scanf("%c",&c1); // line 3 printf("Enter another char: "); scanf("%c", &c2); // line 4 printf("Done"); // line 5 system("PAUSE"); … Read more

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

Do I cast the result of malloc?

TL;DR int *sieve = (int *) malloc(sizeof(int) * length); Has two problems in result of malloc. The cast and that you’re using the type instead of variable as argument for sizeof. Instead, do like this: int *sieve = malloc(sizeof *sieve * length); Long version No; you don’t cast the result, since: It is unnecessary, as void * is automatically … Read more