Why code output -1 instead of 1

int main ()  
{  
struct bit{  
 char f1:1;  
 char f2:1;  
};  
struct bit b;  
b.f1= 0x1;   
b.f2 = 0x1;   
printf("%d\n",b.f1);  
return 0;  
} 

compiled using gcc code -1 outputs. Shouldn't it be 1? Is it because I compile on a small Entian machine?

Added: during debugging using GDB, I see that the value after initializing the structure elements is -1. that is -1 before printing. The following is a listing from GDB:
(gdb) pb
$ 7 = {f1 = -1``, f2 = -1 ''}

Let me know if you need additional debug commands. Provide commands for this.

+3
source share
7 answers

char unsigned signed, . , -, signed, , , int, . , -1 - 11111111 11111111 11111111 11111111 -1 32- int. 1 , 2 2 : 0 1, 0 -1.

EDIT: C 6.2.5, 15: char, char unsigned char . char , , char, char.35

35) CHAR_MIN, limits.h, 0 SCHAR_MIN, . char .

+8

. , 1 , -1. ​​

+3

Skizz tristopia: C99, C, signed unsigned int bool (aka _Bool). - , . , , int, . bool, unsigned, .

+1

'unsigned xxxxx'.

[]
- , ; - "" "" , , .

. ? 0 1 ( , ). , -1, 0, 1 . - . , , .

int, . .
, . . , SO, " "
[/]

To 'R.', re: "... , ".

#include <stdio.h>
int main ()
{
   struct bit{
      char f1:1;
      unsigned char f2:1;
   };
  struct bit b;
  b.f1 = 1;
  b.f2 = 1;
  printf("%d\n",b.f1);
  printf("%d\n",b.f2);
  return 0;
}

, :

-1
1
0

, KevinDTimm - , unsigned name:x.

, , : . gcc ( unsigned char, :

struct bit 
{
   char f1;
   char f2;
};

char (4 ), (1 = neg, 0 = pos). , , . .

, . , , .

0

. , unsigned int.

0

I don’t know C. very well. For example, I don’t know what is doing :1in char f1:1, but I managed to get this code to work on my PC by deleting it:

#include <stdio.h>

int main ()
{
 struct bit{
  char f1;
  char f2;
 };

 struct bit b;

 b.f1 = 0x1;
 b.f2 = 0x1;
 printf("%d\n",b.f1);
 return 0;
}

The result is below:

chooper@brooklyn:~/test$ gcc -o foo foo.c
chooper@brooklyn:~/test$ ./foo
1

Hope this helps you!

-1
source

Source: https://habr.com/ru/post/1771744/


All Articles