简体   繁体   中英

Can't initialize int at 0 in c

I'm making a program for image treatment and i have this variables initialized:

int minR, minG, minB = 255; int maxR, maxG, maxB = 0;
  printf("%d", maxG);

And when I print this, instead of getting a 0 as it should be, I get 16384 as the value of maxG. Yet, if I do this:

int minR, minG, minB = 255; int maxR, maxB = 0;
  int maxG = 0; printf("%d", maxG);

Then everything goes OK.

Does anyone know why this could be? Thank you.

The initializer only applies to the one declarator which it follows, not any of the other declarators in the list!

So int a = 10, b, * c = NULL; only initializes a and c , but b remains uninitialized.

(By the way, reading an uninitialized variable has undefined behaviour .)

int maxR, maxG, maxB = 0;

This becomes:

int maxR;
int maxG;
int maxB = 0;

So MaxR and MaxG are not initialized.

int maxR, maxG, maxB = 0;   

Here only maxB is initialized to 0 .

Easier ways to detect this:
Compile with -Wall or -Wextra .

int minR, minG, minB = 255; int maxR, maxG, maxB = 0;
printf("%d", maxG); 

$ gcc -o exe -Wextra
warning: ‘maxG’ is used uninitialized in this function [-Wuninitialized]

Easier Way to do this:

int maxR, maxG, maxB;
maxR = maxG = maxB = 0;

Where the first line is declaration.
Following line is assignment, evaluated left-to-right.

(maxR = (maxG = (maxB = 0)));
int minR, minG, minB = 255; int maxR, maxG, maxB = 0;
  printf("%d", maxG);

is like

int minR;
int minG;
int minB = 255;
int maxR;
int maxG;
int maxB = 0;
printf("%d", maxG);

but maxG is not initialized so it points somewhere in your memory. 16384 is the real value maxG when you tried to print it but it can be anything!

imagine my memory is like this XXXXXXXX919A9F7B62A526XXXXXX

imagine that when you did

int maG;

the allocated memory for it points here

XXXXXXXX919A9F7B62A526XXXXXX
          ^

since I assume that you system is telling that sizeof(int) is 4 * 8 bits, the printf will print

XXXXXXXX919A9F7B62A526XXXXXX
          ^^^^^^^^
          1o2o3o4o

9A9F7B62 (in hexadecimal) = 2594143074 (in decimal)

So you need to initialize maxG to something before printing it ! :)

您需要初始化所有变量。

int minR = 255, minG = 255, minB = 255; int maxR = 0, maxG = 0, maxB = 0;

The statement should be like this:

int minR = 255, minG = 255, minB = 255; int maxR = 0, maxG = 0, maxB = 0;

maxG in your statement remains uninitialized..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM