1

What is the difference between the following two ways of declaring variables in terms of performance??

1)

#include <iostream>

int main()
{
    int x;//variable inside
    //process
    return 0;
}

2)

#include <iostream>

int x;//variable outside
int main()
{
    //process
    return 0;
}
bartop
  • 9,971
  • 1
  • 23
  • 54

3 Answers3

1

Declaring a variable outside main function means that variable is global, while the one declared inside main is local. This is called "scope" and the concept applies to more than just main function. A better description of this can be found here and here.

Theodor Badea
  • 465
  • 2
  • 9
1

Global variables are defined outside. They hold their value throughout the lifetime of your program. A global variable can be accessed by any function. It is available for use throughout your entire program after its declaration. This is called static duration. Variables with static duration are sometimes called static variables.

There are mainly two types of variable scopes: - Your first part of the code is local variable for main(). You cant use int x outside of main(){} - Second one is called global variable

Also unlike local variables, which are uninitialized by default, static variables are zero-initialized by default.

  • @user12747712 Use this links for more information: http://www.cplusplus.com/forum/beginner/110077/ https://www.learncpp.com/cpp-tutorial/introduction-to-global-variables/ – Sargis Khachatryan Jan 20 '20 at 12:33
0

Check this,

As @Theodar explained Declaring a variable outside main is global and inside main is local. I wanted to explain the performance comparison using them.

  • Making the variable static may incur a small cost on every call of the function determining if the object was already initialized, especially with C++11 where the initialization is thread-safe. Even if it doesn't need a check, the stack is likely to be in cached memory while a static variable is not.

  • Making a variable global will increase the chances that it isn't in cached memory, i.e., there is a good chance that it will be slower (aside from adverse another potential like making it a good candidate to introduce data races).

Hope this will help you more.

Saurav Rai
  • 2,171
  • 1
  • 15
  • 29