What functions can access a global variable that appears in the same file with them?

64 views Asked by At

I asked ChatGPT and Google Bard a C++ question that "What functions can access a global variable that appears in the same file with them?"

They answered that "Any function within the same file where the global variable is declared can access that global variable. Global variables have program-level scope, which means they are accessible from any part of the program within the same program (file). Whether a function is defined before or after the global variable declaration, it can still access and modify that variable."

I was expecting that I can access the global variable in a function defined before the declaration of global variable but I am not able to access it. IDE throws this error:

error: 'x' was not declared in this scope cin >> x;

Did ChatGPT and Google Bard answered wrong or there is any other problem with my code?

My code :

#include <iostream>
using namespace std;
int myFun()
{ 
    return x*2;
}
int x;
int main() {
    cout << "Enter value in global variable: ";
    cin >> x;
    cout << myFun();
    return 0;
}
1

There are 1 answers

0
463035818_is_not_an_ai On

For reference, this is the complete error message from gcc for your code (see here):

<source>: In function 'int myFun()':
<source>:5:12: error: 'x' was not declared in this scope
    5 |     return x*2;
      |            ^

Nothing more. And gcc is correct. You cannot use x before it has been declared. C++ code is parsed top to bottom (templates aside). There is no other mistake in your code.

cin >> x; should not be an error, because it appears after you declared x.

Chat bots can assist you but they can not teach you how a language works. Do not rely on what they say to gain knowledge.