0

I did google and found that n= 1,2,4,8 are only valid arguments to the preprocessor directive #pragma pack(n).

Can someone tell me please what's wrong with the values other than the above-mentioned values? (ex- n=3,5, etc why invalid)?

Are the above-mentioned values the only values which can be taken as an argument?

How the values of n are taken and why?

I am using GCC compiler.

Abhishek Jaiswal
  • 288
  • 2
  • 14
  • What compiler is this for? – Shawn May 08 '21 at 02:23
  • 3
    Technically all values are valid, but some dont make sense. Few hardware systems have data-types that are three or six bytes, for example. It's usually a power of two. – Some programmer dude May 08 '21 at 02:28
  • @Shawn Sorry forgot to mention, now I have edited my post. – Abhishek Jaiswal May 08 '21 at 02:29
  • `#pragma pack` affects the amount of padding in a struct. The amount of padding is normally determined by the alignment restrictions that the processor imposes. The processor alignment requirements are typically expressed in powers of 2. And that's about it. So the questions for you are: How would n=3 be useful? What purpose would it serve? – user3386109 May 08 '21 at 02:32
  • @user3386109 is there a proper reason for expressing the argument as a power of 2? Also, we can't take much greater value for the power of 2. What does it make sense when we use n=3? – Abhishek Jaiswal May 08 '21 at 02:41
  • 2
    [Suggested reading](https://en.wikipedia.org/wiki/Data_structure_alignment) – user3386109 May 08 '21 at 02:44
  • 2
    @Someprogrammerdude: Not all values are valid. The [GCC documentation](https://gcc.gnu.org/onlinedocs/gcc-11.1.0/gcc/Structure-Layout-Pragmas.html#Structure-Layout-Pragmas) says the value is “always is required to be a small power of two.” – Eric Postpischil May 08 '21 at 09:05
  • @trincot Actually, I have got the answer to the problem. So, I deleted the post. But you are saying that you have an answer to the problem, so I have undeleted (undo) my post. Now, you can post your answer there. – Abhishek Jaiswal May 10 '21 at 05:12

1 Answers1

1

Here are three reasons the alignment must be a small power of two.

  1. The GCC documentation says so: The pack value is “always is required to be a small power of two.”

  2. C 2018 6.2.5 4 says alignment must be a power of two: “Every valid alignment value shall be a nonnegative integral power of two.” There is additional text in the clause about maximum alignment (thus limiting it to small powers of two), but it is flexible.

  3. Memory is addressed and organized using binary. Fetching data from memory uses address bits to activate parts within memory devices and to select bytes within words or other groups of bytes. So the alignment boundaries between groupings are located where low bits change. This means the low n address bits for the first byte of a new group are zeros, so the address is a multiple of 2n.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312