c - MinGW with GCC on Windows misreporting numeric values -


for reason, whenever use numeric value in compiler set-up (mingw on windows, using cmd prompt compile , run), misreports numbers in program.

code example:

//c hello world example #include <stdio.h>  int main() {      int value;     value = 10;     printf("the number %d \n"), value;        int value2;      value2 = -100;      printf("the number %d \n"), value2;      return 0; } 

cf. screenshot of output.

by saying

printf("the number %d \n"), value; 

you're somehow making (mis)use of "comma operator" , no syntax error produced. print statement considered as

printf("the number %d \n"); 

and value si executed void expression.

now, printf() being variadic function, not check required number of arguments supplied format specifiers (by default), but, point note, per required format printf(), you're missing out operand %d format specifier. in turn invokes undefined behaviour.

as standard mandates

if there insufficient arguments format, behavior undefined.

the correct syntax be

 printf("the number %d \n", value); 

where value argument %d format specifier.

moral of story: enable compiler warning , pay heed them.


note: suggestions,

  1. the recommended signature of main() int main(int argc, char**argv), or, atleast int main(void).
  2. try habit of defining , initialize variable @ same time. save danger of ending using uninitialized value (local variables) @ later part.

Comments