LoginSignup
1
4

More than 5 years have passed since last update.

c言語_constで注意すべきこと

Last updated at Posted at 2017-05-04
func1.h
#define FUNC1
#ifdef FUNC1
    extern int function1(const char **p);
#endif
func1.c
#include <stdio.h>
#include "func1.h"
#include "func2.h"

int function1(const char **p)
{
        function2(p);
        return (0);
}
func2.h
#define FUNC2
#ifdef FUNC2
    extern int function2(char **p);
#endif
func2.c
#include <stdio.h>
#include "func2.h"

int function2(char **p)
{
    printf("*p=%p\n", *p);
    *p = *p + 1;
    printf("*p=%p\n", *p);
    return(0);
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "func1.h"
#include "func2.h"

int main(int argc, const char *argv[]) {

    const char *name = "tanaka";

    printf("name=%s\n", name);
    function1(&name);
    printf("name=%s\n", name);
    return(0);

}

コンパイル結果:


% gcc -c func1.c -Wall

func1.c:7:12: warning: passing 'const char **' to parameter of type 'char **' discards
      qualifiers in nested pointer types [-Wincompatible-pointer-types-discards-qualifiers]
        function2(p);
                  ^
./func2.h:3:33: note: passing argument to parameter 'p' here
    extern int function2(char **p);
                                ^
1 warning generated.

実行結果:

main.o
name=tanaka
*p=0x106215f9e
*p=0x106215f9f
name=anaka

function2がfunction1から呼ばれている場合、function1の引数をconstとしてしまうと、function2の引数もconstにしなければならなくなる。下手をするとfunction2が使えないという状況も出てくる。

function1とfunction2が別の開発者により開発されている場合、function1の開発者からの指摘がなければfunction2の引数がconstされない可能性がある。

コンパイルするとwarningは出るが、main.oは普通に動いてしまう。
関数が深くネストする場合には、constの使用は控えるのがよい。
  
参考:

C言語入門書の次に読む本

 
 
 
 どやっ!

1
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4