制作一个c ++编译器。传递int而不是一个cont int函数 [英] Fooling a c++ compiler. Passing int instead of a cont int into function

查看:221
本文介绍了制作一个c ++编译器。传递int而不是一个cont int函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 int 传递给期望使用 const int 的函数。

How can i pass an int into a function that is expecting a const int.

有修改cont int值的方法?

Or is there a way of modifying cont int value?

编辑:我应该早些时候提到,我使用ccs c编译器,用于编程PIC微控制器。 fprintf函数将常量流作为其第一个参数。它只接受一个常量int并抛出一个编译错误,否则Stream必须是一个在有效范围内的常量。

I Should have mentioned this earlier, i am using ccs c compiler that is used to program pic microcontroller. fprintf function takes constant stream as its first argument. It will only accept a constant int and throw a compilation error otherwise "Stream must be a constant in the valid range.".

编辑2:流是一个常数字节。

Edit 2: Stream is a constant byte.

推荐答案

函数参数列表中的顶层 const ,所以

A top level const in a function parameter list is completely ignored, so

void foo(const int n);

void foo(int n);

所以,你只需传递一个 int

So, you just pass an int.

唯一的区别是在定义中, n const ,在第二个例子中是可变的。因此,这个特殊的 const 可以看作是一个实现细节,应该在函数声明中避免。例如,这里我们不想修改函数中的 n

The only difference is in the function definition, in which n is const in the first example, and mutable in the second. So this particular const can be seen as an implementation detail and should be avoided in a function declaration. For example, here we don't want to modify n inside of the function:

void foo(int n); // function declaration. No const, it wouldn't matter and might give the wrong impression

void foo(const int n) 
{
  // implementation chooses not to modify n, the caller shouldn't care.
}

这篇关于制作一个c ++编译器。传递int而不是一个cont int函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆