如何使用此const? [英] How is this const being used?

查看:63
本文介绍了如何使用此const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 C完全参考,由Herbert Schildt撰写,并停留在 const解释由指针*他与const解释同时使用。
是他使用的代码:

I was studying "C complete reference" by Herbert Schildt and got stuck on the "const" explanation due by the pointer * he used at the same time with the const explanation. here is the code he used:

#include <stdio.h>

void dash(const char *str);

int main()
{
    dash("this is a test");
    return 0;
}

void dash(const char *str)
{
    while (*str)
    {
        if (*str == ' ')
        {
            printf("%c", '-');
        }
        else
        {
            printf("%c", *str);
        }
        str++;
    }
}

我尝试搜索指针*并得到了一些答案地址,但为什么在此示例中使用它?他的书没有对此进行解释,因此我还没有找到使用指针*的其他示例。
另一个问题是,为什么循环 while(* str)

I've tried to search about the pointer * and got some answers about adresses but why did he use it in this example? His book didn't explain this and i haven't found other examples with this kinda use of pointer *. Other question is, why is the loop "while (*str)" correct if it has no condition?

推荐答案

const char * str 参数声明表明该函数将不会尝试修改 str 指针指向的值。这意味着您可以使用常量字符串来调用该函数。如果声明中没有 const ,则意味着该函数可能会修改字符串,因此只能使用可写字符串来调用它。

const char *str in a parameter declaration indicates that the function will not try to modify the values that the str pointer points to. This means that you can call the function with a constant string. If you don't have const in the declaration, it means that the function might modify the string, so you can only call it with writable strings.

例如,像 strcpy()这样的函数声明第二个参数具有 const (源字符串),但不在第一个参数(目标)上。它可以(通常确实)修改目标,但不能修改源。

As an example, a function like strcpy() declares has const on the second parameter (the source string), but not on the first parameter (the destination). It can (and usually does) modify the destination, but not the source.

这篇关于如何使用此const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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