Thread: Eliminate Padding using normal variables (not structures)

  1. #1
    Registered User
    Join Date
    Jun 2020
    Posts
    1

    Eliminate Padding using normal variables (not structures)

    Yesterday i learned what padding is, i know it happens in structures but iīve also realized it happens when you declare variables that donīt have the same size, for example:
    int a;
    char b;
    int c;
    I understand why this happens, and i know that you can activate #pragma pack() to disable padding in structures; just because Iīm curious, can you eliminate padding with how all variables are allocated?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You probably already know this, but just in case: re-ordering the declarations to reduce the need for padding for alignment would generally be something to reach for before something like #pragma pack, and this should apply for variables not within a struct declaration too.

    On the other hand, I don't think this usually comes up because the savings are unlikely to be worth the effort, whereas it can matter for structs as there could be an array of them, so the wasted bytes easily add up.
    Last edited by laserlight; 06-06-2020 at 08:36 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Doubt regarding structure padding and normal variable
    By karthik537 in forum C Programming
    Replies: 6
    Last Post: 10-03-2012, 08:26 AM
  2. difference between variables and normal text
    By kocmohabt33 in forum C++ Programming
    Replies: 9
    Last Post: 09-28-2010, 01:24 PM
  3. Normal maps: Get normal x/y/z from color
    By Devils Child in forum Game Programming
    Replies: 2
    Last Post: 08-09-2009, 12:01 PM
  4. Question about variables in structures
    By Donarstan in forum C Programming
    Replies: 1
    Last Post: 03-23-2008, 04:43 AM
  5. Padding structures
    By johnnie2 in forum C++ Programming
    Replies: 1
    Last Post: 12-13-2002, 05:03 PM

Tags for this Thread