In C, <<Question about operator (light question!)

Asked 2 years ago, Updated 2 years ago, 83 views

#include <stdio.h>

int main(void) {
    int num1 = 8,num2 = 0; 
    int num3 = num1 << 2;

    printf("num1 = %d\n",num1);
    num1 << 2;
    printf("num1<<2 = %d\n",num1);   // A
    num2 = num1 << 2;
    printf("num2 = %d\n",num1);      // B

    printf("num3 = %d\n",num3);      // C

    return 0;
}

 Execution result: 
num1 = 8
num1<<2 = 8
num2 = 8
num3 = 32

The meaning of num1<<2 is Return the result of moving the bit string of num1 to the left by 2 spaces Isn't it?

Since it returns after the bit operation, the value of num1 does not change, so we found that num1 is 8. (Note A)

But the question arises in (Comment B) and (Comment C).

num2 substituted the bit operation value through the substitution operator after the declaration

num3 replaced the bit operation value when initializing at the same time as the declaration.

I think num2 or num3 should be 32 but the result is not.

Why is this happening?

bit-shift c

2022-09-20 17:10

1 Answers

It's because there's a typo.

printf("num2 = %d\n",num1);      // B

Please correct the code above and execute it as below.

printf("num2 = %d\n",num2);      // B


2022-09-20 17:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.