-1
#include<stdio.h>

int main() {

    int A=1,B=4,C=3,D=3;

    int res1=A-B;

    int res2=B-D;

    if(res1<0){
        int res1=(-1)*res1;
        if(res1>=res2){
            printf("%d\n",res1);
        }
    }
}

I want the res1 as an absolute value(eg:-5 will be assigned as 5) but when execute the code there output terminal is blank. Please reply me want is wrong with my logic.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

2

The if block introduces inner scope and declaration of res1 in the inner scope will hide the res1 declared and defined in the outer scope. Within the if block wherever you use res1, it will be the res1 declared in inner scope and not the one in the outer scope.

Also, in this statement of if block,

    int res1=(-1)*res1;

the uninitialised res1 is used in the expression used to initialise it. In the context of your program, this is undefined behaviour (curious to know why!, check this and this).

To fix the problem, either follow the suggestion given in the comment i.e. don't redeclare the res1 in if block or you can also use standard library function abs() to get the absolute value of res1:

    if ((res1 < 0) && (abs(res1) >= res2)) {
        printf("%d\n", abs(res1));  //assuming you want to print absolute value of res1
    }

Note that, to use standard library function abs(), stdlib.h header file need to include in the program.

H.S.
  • 11,654
  • 2
  • 15
  • 32