const int到int不能正常工作

时间:2018-02-05 11:31:25

标签: c const mplab

如果我在const int内将int转换为void,则可以使用 但是当我创建一个extern const int时却没有。

void ReadFromEpprom()
{
  int Start = 343;
  const int End=Start; //This works
}

示例2

标头文件

extern const int End;

源文件

const int End;

void ReadFromEpprom()
{
  int Start = 343;
  End=Start; //This doesn't work
}

在第二种情况下,我收到错误:

  

(364)尝试修改对象限定的const

我该如何解决这个问题? 我应该用另一种方式吗?

4 个答案:

答案 0 :(得分:0)

当你声明一个常量变量时​​,这意味着变量不会改变。因此,必须立即初始化常量变量是有道理的。你在第一个例子中这是正确的。在你的第二个例子中你有一个常量变量然后你试图修改它的值。这是不正确的,因为变量已经是常数。

答案 1 :(得分:0)

extern这里是一只红鲱鱼。

如果您使用const int End,则需要在此声明时初始化End。那是因为它是const

所以const int End = Start;工作正常,但const int End;在语法上不可行。

在C语言中,您无法安排事情,因此您在全局范围内拥有const,并且在运行时设置值。但是你可以做的是将值嵌入函数(如static),并调用该函数进行初始化并随后检索该值。

答案 2 :(得分:0)

初始化与分配:

可以初始化const对象(在声明处给定值),但不分配(稍后给定值)。

这是初始化,“工作”。它初始化End内存在的局部变量ReadFromEpprom()

void ReadFromEpprom()
{
  ...
  const int End=Start; //This works

End=Start;尝试在End之外的文件范围内分配ReadFromEpprom()。无法分配const个对象。

const int End;

void ReadFromEpprom()
{
  ... 
  End=Start; //This doesn't work
}
  

我该如何解决这个问题?

让外部代码通过函数localEnd阅读ReadEnd(),但允许本地代码编写localEnd

static int localEnd;

int ReadEnd() {
  return localEnd;
}

void ReadFromEpprom() {
  int Start = 343;
  localEnd = Start;
}

答案 3 :(得分:0)

我同意所有其他答案。

您似乎想要初始化import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import table raw_data = {'FLAG' : ['AT-NBBO', 'BETTER-THAN-NBBO', 'ONE-SIDED-QUOTE', 'OUTSIDE-NBBO', 'OUTSIDE-NBBO-DUE-TO-OVERSIZED-BUT-NO-EXECUTION-WITHIN-NBBO', 'OUTSIDE-NBBO-DUE-TO-OVERSIZED-BUT-SOME-EXECUTION_WITHIN_NBBO'], 'COUNT' : [10840, 8628, 84, 633, 153, 14] } df = pd.DataFrame(raw_data, columns = ['FLAG', 'COUNT']) fig, (ax1,ax2) = plt.subplots(ncols=2,figsize=(16,6), gridspec_kw={"width_ratios":[1,2.]}) fig.subplots_adjust(left=0.05, right=0.97, wspace=0.4) ax1.set_aspect("equal") df.plot(kind='pie', y = 'COUNT', ax=ax1, autopct='%1.1f%%', startangle=90, shadow=False, labels=df['FLAG'], legend = True, fontsize=14) ax2.axis("off") tbl = table(ax2, df, loc='center',colWidths=[0.9,0.10]) print tbl tbl.auto_set_font_size(False) plt.show() 值,其值将在运行时确定,不可能

你可以做的是两个解决方法。

  1. 删除const。在其定义附近添加注释,该变量一开始只设置一次。
  2. 使用函数而不是const变量;只执行一次"运行代码"这个功能里面的想法。

    标题文件:

    const int

    源文件:

    int CalcEnd();
    

    注意该函数如何使用int CalcEnd() { static int init_done = 0; static int result; if (!init_done) { result = 343; // or any complex calculation you need to do init_done = 1; } return result; } 变量和逻辑只进行一次初始化。

  3. 如果您使用功能构思,并且不想记住在函数调用(static)中键入括号,则可以定义宏:

    CalcEnd()

    这会使#define End MyCalcEnd() 变为End变量,而实际上它是一个函数调用。这种宏的使用是有争议的,只有在你确定它不会导致以后混淆时才使用它。

相关问题