Like us on Facebook

News: If you feel any problem while posting a topic or Reply - Contact our server team at: +92-341-2825535

Author Topic: The following program fragment unsigned i = 1;  (Read 262 times)

Offline mechanic

  • Engineer
  • Hero Engineer
  • *****
  • Posts: 2253
    • View Profile
    • Engineering Forum
The following program fragment unsigned i = 1;
« on: February 28, 2017, 07:45:59 AM »
Advertisement
Question: The following program fragment

unsigned i = 1;
int j = -4;
printf("%u", i + j);


prints

Options are:


A. garbage
B. -3
C. an integer that changes from machine to machine
D. none of the above

Correct answer is:

C. an integer that changes from machine to machine

Explanation:


In the computer I used to excute this program, the output was 4294967293. That's because in my system, sizeof(int) is 4 bytes (32 bits), and negative numbers are represented in 2's complement form. This means -4 will be represented as 11111111 11111111 11111100 (i.e. 30 one's followed by 2 zeroes). Note that this number is 232 -1 -3. before j gets added to i, it will be converted to an unsigned integer, so, i + j is essentially adding 1 to 232 - 1 - 3, which gives 4294967293.


Engineering Forum

The following program fragment unsigned i = 1;
« on: February 28, 2017, 07:45:59 AM »
Like us on Facebook

 

With Quick-Reply you can write a post when viewing a topic without loading a new page. You can still use bulletin board code and smileys as you would in a normal post.

Warning: this topic has not been posted in for at least 120 days.
Unless you're sure you want to reply, please consider starting a new topic.

Name: Email:
Verification:
Type the letters shown in the picture
Listen to the letters / Request another image
Type the letters shown in the picture:
type: "Pakistan" without quotes: