top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why the following C code gives output: -2 -1 instead of 2 1?

+2 votes
496 views
struct marks {
  int a:1;
  int b:2;
};

int main() {
  struct marks obj={1,6};
  printf("%d %d\n",obj.b,obj.a);
}
posted Apr 28, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

This question is not as simple as it looks. What I interpreted that first field a and second field b both are signed integer type. If I consider a short int as 1 byte then its left most bit would signify (+/-) based on either left most bit is 0 or 1.
In this case though only one bit is reserved for member "a "but this bit would be considered for signed/unsigned also that's why when value 1 is assign to "a" and when it is printed it shows as -1.
Same concept of member "b" also.

answer Apr 29, 2017 by Harshita
Similar Questions
+3 votes

See the following code

void main(){
   float a=5.2;
  if(a==5.2)
     printf("Equal");
  else if(a<5.2)
     printf("Less than");
  else
     printf("Greater than"); 
}

Expected output is equal but we does not get same why?

0 votes

Write a C code for the logic -
input: string, strong
output: strng

...