这个 const 是如何使用的? [英] How is this const being used?

查看:15
本文介绍了这个 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天全站免登陆