定义整数(int);默认值是多少?

发布于 2024-10-09 08:34:22 字数 156 浏览 5 评论 0原文

int i;
int data[5] = {0};
data[0] = i;

data[0] 的值是多少?

另外,这一行的含义是什么?

if (!data[0]) { ... }
int i;
int data[5] = {0};
data[0] = i;

What's the value in data[0]?

Also, what's the meaning of this line?

if (!data[0]) { ... }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

定格我的天空 2024-10-16 08:34:22

在大多数情况下,int 对象没有“默认”值。

如果将 int i; 声明为函数内部的(非静态)局部变量,则它具有不确定的值。它尚未初始化,在向其写入有效值之前您无法使用它。

在声明任何对象时显式初始化它是一个好习惯。

In most cases, there is no "default" value for an int object.

If you declare int i; as a (non-static) local variable inside of a function, it has an indeterminate value. It is uninitialized and you can't use it until you write a valid value to it.

It's a good habit to get into to explicitly initialize any object when you declare it.

烟酉 2024-10-16 08:34:22

这取决于代码写在哪里。考虑一下:

int i;
int data[5] = {0};

void func1(void)
{
    data[0] = i;
}

void func2(void)
{
    int i;
    int data[5] = {0};
    data[0] = i;
    ...
}

func1() 中分配给 data[0] 的值是完全确定的;它必须为零(假设没有其他赋值干扰全局变量 idata 的值)。

相比之下,func2() 中设置的值是完全不确定的;您无法可靠地说明将分配给 data[0] 的值,因为函数中没有可靠地分配给 i 的值。它可能是来自先前函数调用的堆栈上的值,但这取决于编译器和程序,甚至不是“实现定义的”;这是纯粹的未定义行为。

您还会问“这是什么意思?”

if (!data[0]) { ... }

!”运算符对其所应用的值进行逻辑反转:它将零映射到一,并将任何非零值映射到零。如果表达式计算结果为非零值,则总体条件计算为 true。因此,如果 data[0] 为 0,则 !data[0] 映射为 1,并且执行块中的代码;如果 data[0] 不为 0,则 !data[0] 映射为 0,并且不执行块中的代码。

这是一个常用的习语,因为它比其他习语更简洁:

if (data[0] == 0) { ... }

It depends on where the code is written. Consider:

int i;
int data[5] = {0};

void func1(void)
{
    data[0] = i;
}

void func2(void)
{
    int i;
    int data[5] = {0};
    data[0] = i;
    ...
}

The value assigned to data[0] in func1() is completely deterministic; it must be zero (assuming no other assignments have interfered with the values of the global variables i and data).

By contrast, the value set in func2() is completely indeterminate; you cannot reliably state what value will be assigned to data[0] because no value has been reliably assigned to i in the function. It will likely be a value that was on the stack from some previous function call, but that depends on both the compiler and the program and is not even 'implementation defined'; it is pure undefined behaviour.

You also ask "What is the meaning of this?"

if (!data[0]) { ... }

The '!' operator does a logical inversion of the value it is applied to: it maps zero to one, and maps any non-zero value to zero. The overall condition evaluates to true if the expression evaluates to a non-zero value. So, if data[0] is 0, !data[0] maps to 1 and the code in the block is executed; if data[0] is not 0, !data[0] maps to 0 and the code in the block is not executed.

It is a commonly used idiom because it is more succinct than the alternative:

if (data[0] == 0) { ... }
江湖彼岸 2024-10-16 08:34:22

如果全局声明一个整数,那么它会自动用零初始化
但如果它是本地的则包含垃圾值,直到并且除非它被赋予了一些值

if an integer is declared globally then it is initialized automatically with zero
but if it is local then contains garbage value until and unless itis given some value

疧_╮線 2024-10-16 08:34:22

如果整数未初始化,则其值根据 C 未定义

If an integer is not initialized, its value is undefined as per C

孤单情人 2024-10-16 08:34:22

由于您已包含 ={0};,因此整个数组都用零填充。如果这是在任何函数外部定义的,即使没有初始化程序,它也将被初始化为零。 if (!data[x]) 相当于 if (data[x] == 0)

Since you've included the ={0};, the entire array is filled with zeros. If this is defined outside any function, it would be initialized with zeros even without the initializer. if (!data[x]) is equivalent to if (data[x] == 0).

日裸衫吸 2024-10-16 08:34:22

// 文件 'ac'

   #include <stdio.h> 

   void main()
    {
            int i, j , k;
            printf("i = %i j = %i k = %i\n", i, j, k);
    }

// 测试结果

> $ gcc a.c 
> $ ./a.out 
> i = 32767 j = 0 k = 0

// File 'a.c'

   #include <stdio.h> 

   void main()
    {
            int i, j , k;
            printf("i = %i j = %i k = %i\n", i, j, k);
    }

// test results

> $ gcc a.c 
> $ ./a.out 
> i = 32767 j = 0 k = 0
彻夜缠绵 2024-10-16 08:34:22

正如@James McNellis 在 2010 年所说,编程语言的标准将变量的初始值留给编译器实现,并且不同编译器实现的结果有所不同。

我来这里是为了回顾这方面的情况,因为我记得观察到一些编译器将整数数组初始化为零。

在阅读了此处记录的不确定答案后,我在程序集中构造了一个小型静态方法,在生产代码中实现一项技术之前,我用它来进行此类实验。我当前的项目需要将一些 JavaScript 代码移植到 C#。由于 JavaScript 解释器不初始化任何内容,因此该实现以 FOR 循环打开来初始化一个大型整数数组。在我盲目地把它留在 C# 实现中之前。

方法如下。

        private static void IntegerArrayGym ( )
    {
        int [ ] ints = new int [ 10 ];

        Console.WriteLine ( $"{TEST_INTEGER_ARRAY_GYM} Begin:{Environment.NewLine}" );

        int intArrayLength = ints.Length;

        Console.WriteLine ( $"    The test array consists of {ints} uninitialized integers.{Environment.NewLine}" );

        for ( int intJ = ArrayInfo.ARRAY_FIRST_ELEMENT;
                  intJ < intArrayLength;
                  intJ++ )
        {
            Console.WriteLine ( $"    Value of integer at ordinal position {ArrayInfo.OrdinalFromIndex ( intJ )} = {ints [ intJ ]}" );
        }   // for ( int intJ = ArrayInfo.ARRAY_FIRST_ELEMENT; intJ < intArrayLength; intJ++ )

        Console.WriteLine ( $"{Environment.NewLine}{TEST_INTEGER_ARRAY_GYM} Done!" );
    }   // private static void IntegerArrayGym

输出如下。

CSharp_Lab,版本 7.92.170.0
开始 @ 03/06/2023 22:58:49.124 (03/07/2023 04:58:49.124 UTC)

IntegerArrayGym 开始:

The test array consists of System.Int32[] uninitialized integers.

Value of integer at ordinal position 1 = 0
Value of integer at ordinal position 2 = 0
Value of integer at ordinal position 3 = 0
Value of integer at ordinal position 4 = 0
Value of integer at ordinal position 5 = 0
Value of integer at ordinal position 6 = 0
Value of integer at ordinal position 7 = 0
Value of integer at ordinal position 8 = 0
Value of integer at ordinal position 9 = 0
Value of integer at ordinal position 10 = 0

IntegerArrayGym 完成!
请按 ENTER(回车)键退出程序。

As @James McNellis stated in 2010, the standards for programming languages leave the initial value of a variable to the compiler implementation, and results differ from one compiler implementation to another.

I came here to review the state of affairs in this regard because I remembered observing that some compilers initialize arrays of integers to zero.

After reading the inconclusive answers recorded here, I constructed a small static method in the assembly that I use to conduct such experiments before I implement a technique in production code. My current project requires porting some JavaScript code to C#. Since the JavaScript interpreter doesn't initialize anything, that implementation opened with a FOR loop to initialize a large array of integers. Before I blindly left it in the C# implementation.

The method follows.

        private static void IntegerArrayGym ( )
    {
        int [ ] ints = new int [ 10 ];

        Console.WriteLine ( 
quot;{TEST_INTEGER_ARRAY_GYM} Begin:{Environment.NewLine}" );

        int intArrayLength = ints.Length;

        Console.WriteLine ( 
quot;    The test array consists of {ints} uninitialized integers.{Environment.NewLine}" );

        for ( int intJ = ArrayInfo.ARRAY_FIRST_ELEMENT;
                  intJ < intArrayLength;
                  intJ++ )
        {
            Console.WriteLine ( 
quot;    Value of integer at ordinal position {ArrayInfo.OrdinalFromIndex ( intJ )} = {ints [ intJ ]}" );
        }   // for ( int intJ = ArrayInfo.ARRAY_FIRST_ELEMENT; intJ < intArrayLength; intJ++ )

        Console.WriteLine ( 
quot;{Environment.NewLine}{TEST_INTEGER_ARRAY_GYM} Done!" );
    }   // private static void IntegerArrayGym

The output follows.

CSharp_Lab, version 7.92.170.0
Begin @ 03/06/2023 22:58:49.124 (03/07/2023 04:58:49.124 UTC)

IntegerArrayGym Begin:

The test array consists of System.Int32[] uninitialized integers.

Value of integer at ordinal position 1 = 0
Value of integer at ordinal position 2 = 0
Value of integer at ordinal position 3 = 0
Value of integer at ordinal position 4 = 0
Value of integer at ordinal position 5 = 0
Value of integer at ordinal position 6 = 0
Value of integer at ordinal position 7 = 0
Value of integer at ordinal position 8 = 0
Value of integer at ordinal position 9 = 0
Value of integer at ordinal position 10 = 0

IntegerArrayGym Done!
Please press the ENTER (Return) key to exit the program.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文