0

I have this piece of code, can it ever evaluate to true?

struct type {
    char a;
    int b;
    char c;
    float d;
} t;

char e;
int f;
char g;
float h;

int out = sizeof(t) == sizeof(e) + sizeof(t) + sizeof(g) + sizeof(h);
print("%d", out);
ShadowDoom
  • 94
  • 1
  • 5
  • this `sizeof(e) + sizeof(t) + sizeof(g) + sizeof(h);` you might mean `sizeof(e) + sizeof(f) + sizeof(g) + sizeof(h);` – IrAM Jan 26 '21 at 09:47
  • It _can_ evaluate to true on systems that don't have alignment requirements. That is 8-bit CPUs and some 16-bitters. – Lundin Jan 26 '21 at 09:48
  • Even I was wondering that, but it seems my instructor gave "t" there not "f" – ShadowDoom Jan 26 '21 at 09:49
  • 1
    In that case, the answer is always 0 because all objects have positive size, so subtracting `sizeof(t)` from both sides leaves `0 == sizeof(e) + sizeof(g) + sizeof(h)` (or `0 == some_positive_number`), which is false. – Ian Abbott Jan 26 '21 at 09:54
  • 1
    Uh right, I thought it said `sizeof(e) + sizeof(f) + sizeof(g) + sizeof(h);` but that's not the actual code. Then obviously the expression is never true. Also the duplicate isn't correct. The question is essentially just asking if `2 == 1 + 2 + 3 + 4 + 5` makes sense. No it doesn't... – Lundin Jan 26 '21 at 10:03
  • Simple maths : `x == x + n` will never be the truth for any `n` != 0 – 0___________ Jan 26 '21 at 10:08
  • @IanAbbott if not `pedantic` `sizeof` does not have to be positive. https://godbolt.org/z/W6vrfq – 0___________ Jan 26 '21 at 10:12
  • @0___________ (pedantic) Your example does not conform to the constraints of structure and union specifiers. – Ian Abbott Jan 26 '21 at 11:27
  • @0___________ Or more accurately: zero-length array types are not valid in standard C. If you change it to a flexible array member it then falls foul of the rule that a struct type with a flexible array member at the end must have at least two members. – Ian Abbott Jan 26 '21 at 11:39
  • @IanAbbott off-topic. I am starting to think what actually is more standard? `gcc` standard or ISO standard? :) More and more compilers implement gcc extensions. I vote gcc – 0___________ Jan 26 '21 at 12:13

0 Answers0