开发者

Is the value of i defined after: int i, j = 1;

Given:

int i, j = 1;

Is the value of i defined? If so, what is it?

I suspect this is a duplicate, but it's 开发者_如何学JAVAsomewhat hard to search for - if anyone can find it let me know.


  • Global variables are initialized by default to their default values (0 for int)
  • Local variables are not initialized by default

For example:

#include <iostream>

int a, b=1; // a=0, b=1

int main(void) {
 int p, q=1; // p=undef, q=1
 return 0;
}

proof for local variables:

#include <iostream>
int main(void) {
  {
    int x = 99; // change stack where a would be
  }
  int a, b=0;
  std::cout << a << std::endl;
  return 0;
}


If this code is in global scope, then i will be 0. Otherwise i is not defined.


No, it's not defined, and the compiler should complain if you try to use it, depending on the language.


If this is defining local variables then the value of i won't be defined.


The code you showed is equivalent to:

int i;
int j = 1;

that means, that i is defined, but not initialized.


i will be undefined. This leads to undefined behaviour if you try to use i without assigning it something.

Any good compiler will warn you about stuff like this. Using an undefined variable of type int might be harmless enough, but don't use undefined pointers.

Perhaps not today, but some time ago, before sufficient hardware and software protection, you could damage your machine's BIOS by using pointers with uninitialized variables.

Moral of the story: if it isn't initialized, don't use it.


The variable i can contain anything from 0 to garbage. please refer to the following link

http://www.intap.net/~drw/cpp/cpp03_02.htm for more information


int i is a definition statement, but it is not assigned with a value.

Extern int i is declaration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜