Compile problem

When I am running this code it is giving me the answer 25 but it’s answer should be 34

#include <iostream>
using namespace std;
int main() {
  int b = 34;
  int b = 25;
  int c = ::b;
  cout << c;
  return 0;
}

Expected behavior:
Compiler should print 34 not 25

Actual behavior:
Compiler is printing 25 not 34

Steps to reproduce:
Just type the code that i am giving you

Bug appears at this link:

https://replit.com/@MayankGaming/CPlusPlus?s=app

Browser/OS/Device:
I use chrome browser but now I am using the app.
I am using Android OS
I have a mobile of Vivo company and the

This topic should be under Code Help and not Bug Reports.
Anyway, you replaced the variable b with 25 after assigning it to 34. It was 34, but you then changed it to 25, so c will be 25. If I am not wrong, this is how I understand it.

Does the program work now? @MayankGaming

Bro didn’t you see scope resolution this = :: (scope resolution is used to take the global number instead of local )

I’m a bit confused. None of your variable declarations are globals, and using :: alone results in an error, because you haven’t specified a namespace to access from.

Another thing, why do you even need to access from a namespace? @bigminiboss solution is much simpler than accessing globals and creating a namespace and whatever else

As @NateDhaliwal said, you are overriding b (which used to be 34) with 25, which is the reason why it’s outputting 25.

Here is your improved code if you want to continue using the scope resolution operator:

#include <iostream>
using namespace std;

namespace test {
    int b = 34;
}

int main(){
    int c = test::b;
    cout << c;

    return 0;
}
1 Like

your problem here is that how do that be even compiling. Second, there’s no need to do namespace on primitives. You can just do

int c = b;
2 Likes