Interview Question
Country: United States
can u please help explain why the out put is -2 if I set the width as 2 and assign 2 to it.?
can u please help explain why the out put is -2 if I set the width as 2 and assign 2 to it.?
is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.
CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.
Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.
Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.
Here you are actually setting the width of the variable a as 1bit but since you have declared a as "signed" int, hence it will reserve one bit for the sign of the number. So with a variable 1 bit wide you can just store 0 or -1(as 1 will be considered -1 because 1 is used to indicate the negative sign in signed integers) hence when you try to pass value 1 to a it will actually have a value -1. To get rid of this you can declare your variable unsigned like "unsigned int a:1" will do. Or you can increase the width of a. I hope I am clear.
- Spock July 06, 2012You can also try an example where you set the width of a as 2 and try giving it a value "2". Since the binary representation of 2 is "10", It will treat 1 as a sign bit and will store -0 or 0 as the result.