将struct中的所有变量设置为零/一

时间:2019-01-24 09:38:20

标签: c

我想知道是否可以将结构中存在的所有变量(在LOOP内)初始化为0,然后再初始化为1

这是一个演示程序:

#include <stdio.h>

#define LEDS_LENGTH 7

void inititate_to_zero(void);
void inititate_to_one(void);

struct pins
{
    unsigned char state : 1;
    unsigned char LED0  : 1;
    unsigned char LED1  : 1;
    unsigned char LED2  : 1;
    unsigned char LED3  : 1;
    unsigned char LED4  : 1;
    unsigned char LED5  : 1;
}pins;

int main(void)
{
    inititate_to_zero( );
    inititate_to_one( );
}

void inititate_to_zero(void)
{
    for(unsigned char i = 0; i < LEDS_LENGTH; i++)
    {
        /// set all variable in struct pins to 0;
        pins.VARIABLE[SOME_HOW] ^= ( 1 << 0 );
    }
}

void inititate_to_one(void)
{
    for (unsigned char i = 0; i < LEDS_LENGTH; i++)
    {
        /// set all variable in struct pins to 1;
        pins.VARIABLE[SOME_HOW] ^= ( 1 << 0 );
    }
}

编辑:

如果可能,我需要替换函数inititate_to_one()才能使用LOOP:

#include <stdio.h>

#define LEDS_LENGTH 7

void inititate_to_one ( void );

struct pins
{
    volatile unsigned char state    : 1;
    unsigned char LED0              : 1;
    unsigned char LED1              : 1;
    unsigned char LED2              : 1;
    unsigned char LED3              : 1;
    unsigned char LED4              : 1;
    unsigned char LED5              : 1;
}pins{ 0 };


int main( void )
{
    inititate_to_one ( );
}

void inititate_to_one( void )
{
    state ^= ( 1 << 0 );
    LED0  ^= ( 1 << 0 );
    LED1  ^= ( 1 << 0 );
    LED2  ^= ( 1 << 0 );
    LED3  ^= ( 1 << 0 );
    LED4  ^= ( 1 << 0 );
    LED5  ^= ( 1 << 0 );
}

1 个答案:

答案 0 :(得分:7)

拥有

struct pins
{
    volatile unsigned char state    : 1;
    unsigned char LED0              : 1;
    unsigned char LED1              : 1;
    unsigned char LED2              : 1;
    unsigned char LED3              : 1;
    unsigned char LED4              : 1;
    unsigned char LED5              : 1;
}pins;

将全部设置为0:memset(&pins, 0, sizeof(pins));

将全部设置为1:memset(&pins, -1, sizeof(pins));

也许内存集将被优化为仅设置一个字节


要帮助John Doe:

#include <stdio.h>
#include <string.h>

struct pins
{
    volatile unsigned char state    : 1;
    unsigned char LED0              : 1;
    unsigned char LED1              : 1;
    unsigned char LED2              : 1;
    unsigned char LED3              : 1;
    unsigned char LED4              : 1;
    unsigned char LED5              : 1;
} pins;

void pr()
{
  printf("%u %u %u %u %u %u %u\n",
     pins.state, pins.LED0, pins.LED1, pins.LED2, pins.LED3, pins.LED4, pins.LED5);
}

int main()
{
  /* pins is already to 0 because static */
  memset(&pins, -1, sizeof(pins));
  pr();
  memset(&pins, 0, sizeof(pins));
  pr();
  memset(&pins, -1, sizeof(pins));
  pr();

  return 0;
}

执行:

1 1 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 1 1