DEV Community

sagar.codes
sagar.codes

Posted on

What are local and global variables?

Okay , let me keep it simple and 2 minute read

Imagine you have lil skies music concert in your town and if I ask some true hip hop lover from your town he obviously knows who is lil skies so he is globally more famous, and on the other hand in that same concert to open lil skies management focuses on local talent of your town who is just famous in your town let me call him "Mystery" he started his career a year ago so you know who is Mystery and his work but but in other countries no one knows who Mystery is .

if you understand this story guess what you can easily understand local and global variables

I will explain with code

`#include
using namespace std;

string global = "lil skies";
int main()
{
string global = "Mystery";
cout<<global<<endl;
}`

here as you see before main function we have a global string which gives me lil skies and in main function which is in a block we have Mystery , here block is nothing but Your town based on the above analogy , so what happens is when I do print my output it won't print lil skies , it prints Mystery why in your town only hip hop fans know who is lil skies but everyone doesn't know him , but everyone knows who is mystery because he is from this town he has contributed to this town, right?

So How can I print 'lil skies'? For that, you need to ask the particular hip hop fans; only they know who 'lil skies' is. so in programming we use "::" operator

`#include
using namespace std;

string global = "lil skies";
int main()
{
string global = "Mystery";
cout<<::global<<endl;
}
`
now lil skies gets printed , but usually lil skies wins everytime why because he is a global variable, and he can be called by any function using the :: operator , but mystery is only known by his town so he exist with that main function town if you try to print him outside you get errors because he is not global scoped , he is local scoped.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs