相关疑难解决方法(0)

代表C中的动态类型

我正在写一种动态类型的语言.目前,我的对象以这种方式表示:

struct Class { struct Class* class; struct Object* (*get)(struct Object*,struct Object*); };
struct Integer { struct Class* class; int value; };
struct Object { struct Class* class; };
struct String { struct Class* class; size_t length; char* characters; };
Run Code Online (Sandbox Code Playgroud)

目标是我应该能够将所有内容作为a传递struct Object*,然后通过比较class属性来发现对象的类型.例如,要转换一个整数以供使用,我只需执行以下操作(假设它integer是类型struct Class*):

struct Object* foo = bar();

// increment foo
if(foo->class == integer)
    ((struct Integer*)foo)->value++;
else
    handleTypeError();
Run Code Online (Sandbox Code Playgroud)

问题是,据我所知,C标准没有对如何存储结构做出承诺.在我的平台上这是有效的.但是在另一个平台struct String可能存储value之前class和我foo->class在上面访问时我会实际访问foo->value,这显然很糟糕.便携性是这里的一个重要目标.

这种方法有其他选择:

struct …
Run Code Online (Sandbox Code Playgroud)

c data-representation

12
推荐指数
3
解决办法
3189
查看次数

如何*restrict/*__ restrict__在C/C++中有效吗?

这是我写的一些代码(使用GCC __restrict__对C++ 的扩展):

#include <iostream>

using namespace std;

int main(void) {
    int i = 7;
    int *__restrict__ a = &i;
    *a = 5;
    int *b = &i, *c = &i;
    *b = 8;
    *c = 9;

    cout << **&a << endl; // *a - which prints 9 in this case

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

或者,C版本(如果C++版本由于使用了每个流行的C++编译器支持的扩展而不清楚),使用GCC:

#include <stdio.h>

int main(void) {
    int i = 7;
    int *restrict a = &i;
    *a = 5;
    int *b = &i, *c = &i;
    *b …
Run Code Online (Sandbox Code Playgroud)

c c++

7
推荐指数
1
解决办法
5857
查看次数

标签 统计

c ×2

c++ ×1

data-representation ×1