IS" const int的X = get()方法;"合法使用C?我们能否函数的返回值分配给在声明恒定? [英] Is "const int x = get();" legal in C?Can we assign a function's return value to a constant at declaration?

查看:106
本文介绍了IS" const int的X = get()方法;"合法使用C?我们能否函数的返回值分配给在声明恒定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个高度驰名贡献者R ..在这个论坛上明确地告诉我,这家2天回:

A highly reputed contributor "R.." on this forum explicitly told me this 2 days back:

的初始化静态存储持续时间的对象必须是恒定的前pressions。一个函数调用的结果是不是一个常数前pression。

他在谈论全球variables.But我不知道与该matter.Though的的main()函数内声明的常量,或任何功能发生的事情我凭直觉感觉它是那么即使对职能范围内声明的常量,从以下链接来源,其所谓正确回答下面的程序,是混淆了我。

He was talking about global variables.But I am not sure what goes with constants declared inside the main() function, or any function for that matter.Though intuitively I feel it is so even for constants declared within functions,the following program sourced from the following link, with its supposedly correct answer, is confusing me.

<一个href=\"http://www.indiabix.com/c-programming/const/discussion-546\">http://www.indiabix.com/c-programming/const/discussion-546

#include<stdio.h>
int get();

int main()
{
    const int x = get();
    printf("%d", x);
    return 0;
}

int get()
{
    return 20;
}

因此​​,谁能解释一下其是否有效用C来分配一个返回值一个常数?

So can anyone explain whether it's valid in C to assign a return value to a constant?

推荐答案

是的,这是完全有效的,因为你的变量是自动的,也就是说的静态

Yes, it's perfectly valid, since your variable is automatic, i.e. not static.

该限制适用于静态变量,其值必须在编译时是已知的。

The restrictions apply to static variables, whose values must be known at compile-time.

注意,C恒恩pressions和其他前pressions之间,而用于静态变量初始化值必须是区分这样的恒恩pression。对于非 - 静态变量,也没有这样的规定。

Note that C differentiates between "constant expressions" and other expressions, and that the initializer value used for static variables must be such a constant expression. For non-static variables, there is no such requirement.

这篇关于IS&QUOT; const int的X = get()方法;&QUOT;合法使用C?我们能否函数的返回值分配给在声明恒定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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