I did some C programming couple decades ago. I am trying to re-learn the language. I wrote this. I get something unexpected. When I change the ‘short int’ to ‘int’, it seems to work. Can anyone look at my code to see if anything is wrong with it or is this a compiler issue. I am using gcc on Linux.
#include <stdio.h>
int main(void) {
short int age = 0;
short int num_1_yr_olds = 0;
short int num_2_and_3_yr_olds = 0;
short int num_above_3_yr_olds = 0;
while(1) {
printf ("Enter age: ");
scanf ("%d", &age);
if (age < 1) {
break;
}
switch (age) {
case 1:
++num_1_yr_olds;
break;
case 2:
case 3:
++num_2_and_3_yr_olds;
break;
default:
++num_above_3_yr_olds;
break;
}
}
printf ("Number of 1 year olds = %d\n", num_1_yr_olds);
printf ("Number of 2 and 3 year olds = %d\n", num_2_and_3_yr_olds);
printf ("Number above 3 year olds = %d\n", num_above_3_yr_olds);
}
Input
Enter age: 1
Enter age: 1
Enter age: 1
Enter age: -1
Output
Number of 1 year olds = -1
Number of 2 and 3 year olds = 0
Number above 3 year olds = 0
num_1_yr_olds value is getting messed up. I expected a 3, I get a -1. The value of num_1_yr_olds becomes a -1 regardless of input.
Your problem lies here:
You really need to ensure that your data types match your format string. The correct format specifier for a
short intis%hd, not%d.Some compilers will actually check this and warn you.
What’s likely to be happening is that the misalignment of data and format string is causing the
short intto become the “wrong” value hence the counts are being screwed up.In more depth, for a two’s complement, little-endian architecture like x86, scanning an
intinto ashortmay put the least significant half intoageand the most significant half intonum_1_year_olds(if it’s adjacent toagein memory).Graphically, it may be clearer to think of it like this:
So, when you enter
1,agebecomes1andnum_1_year_oldsbecomes0.Each time you do that, it increases
num_1_year_oldsbecauseageis1but that will be overwritten by thescanfthe next time you get input.When you finally enter
-1(all 1 bits in two’s complement),agebecomes-1and so doesnum_1_year_olds.Then, because
ageis less than one, the loop breaks, and the values are what you see:{-1, 0, 0}.