Why does GCC say that a variable is not used when it is not?

GCC says that snr_db is not used when I set the -Wall flag, but this variable is used. When I initialize it out of scope, gcc stops warning me. Does anyone know why this is?

double snr_db;
double snr_db_step = #WHATHEVER

for (int interval = 1, snr_db = 20.0; interval <= intervals; interval++, snr_db -= snr_db_step) {
    snr_lin = pow(10.0, snr_db / 10.0);
    bit_err_rate = ber_bpsk(snr_lin);
    //CODE CONTINUES
}
+4
source share
4 answers

Existing answers have already examined the root of the problem: this cycle for

for (int interval = 1, snr_db = 20.0; [...]; [...]) {

declares two type variables int, one of which has the shadow of the double snr_dbouter region. For a deeper understanding, add some background.

From N1570 (last draft for C11) , ยง6.8.5.3 p1 :

Statement

        for ( -1 ; -2 ; -3 ) statement

: expression-2 , . -3 void . -1 , , , , ; . -1 , void .

, for, -1 , . . , .

, , , - . for. -1 void, , . , :

[...]
int interval;
for (interval = 1, snr_db = 20.0; [...]; [...]) {

-1 , ( ). , interval .

, , , , :

for (int interval = (snr_db = 20.0), 1; [...]; [...]) {

interval, , snr_db = 20.0, 1 ( ) interval. C, , , . , , .

interval -1 snr_db :

snr_db = 20.0;
for (int interval = 1; [...]; [...]) {
+4

. double -

double snr_db; // this is unused 

for -

for (int interval = 1, snr_db = 20.0; ..)

snr_db int ( , int x,y;, int ), - , .

, double snr_db; .

-

double snr_db;
int interval; 

for(interval = 1, snr_db =20.0;..){....}  // only intialization
 /* ^^^^^^^^^^^^^^^^^^^^^^^^ this would be a different case from above as here
',' does work as comma operator therefore, evaluating both the expressions. */
+12

for int, ( snr_db), double scope. GCC .

( , , GCC, , , )

snr_db = 20.0; for, .

You can use the comma operator , but this will make your code unreadable:

for (int interval = (snr_db = 20.0), 1;  ///unreadable so confusing

therefore, I do not recommend doing this.

+5
source

Reason: snr_db in for loop is a temporary variable and not an external scope variable.

0
source

Source: https://habr.com/ru/post/1687989/


All Articles