gpt4 book ai didi

c - 被误解的代码示例

转载 作者:行者123 更新时间:2023-12-04 10:27:43 24 4
gpt4 key购买 nike

我正在读这本书http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html我停在其中一个例子上。我认为这是不正确的。我认为,没有未定义的行为。我错了吗?在这里:

Taking the address of a data object of a type which isn't const and putting it into a pointer to the const-qualified version of the same type is both safe and explicitly permitted; you will be able to use the pointer to inspect the object, but not modify it. Putting the address of a const type into a pointer to the unqualified type is much more dangerous and consequently prohibited (although you can get around this by using a cast). Here is an example:

#include <stdio.h>
#include <stdlib.h>

main(){
int i;
const int ci = 123;

/* declare a pointer to a const.. */
const int *cpi;

/* ordinary pointer to a non-const */
int *ncpi;

cpi = &ci;
ncpi = &i;

/*
* this is allowed
*/
cpi = ncpi;

/*
* this needs a cast
* because it is usually a big mistake,
* see what it permits below.
*/
ncpi = (int *)cpi;

/*
* now to get undefined behaviour...
* modify a const through a pointer
*/
*ncpi = 0;

exit(EXIT_SUCCESS);
}

Example 8.3 As the example shows, it is possible to take the address of a constant object, > generate a pointer to a non-constant, then use the new pointer. This is an error in your program and results in undefined behaviour.

在这个例子中,ncpi 最终指向i,而不是ci。所以我认为这使得这个例子不正确——在通过指针修改非 const 变量时没有未定义的行为。你同意吗?

最佳答案

我同意:这是一个有缺陷的例子。代码本身表现出定义的行为。

最终赋值前的注释,*ncpi = 0;,与代码不一致。可能作者打算做一些不同的事情。


我的第一 react 是好像代码覆盖了一个const: 我修改了我的答案。

关于c - 被误解的代码示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29996692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com