开发者社区> 问答> 正文

optind参数在printf中的输出和gdb中p的值不一样

问题描述
今天在看getopt_long()的使用时,对optind的不是很理解,就gdb看了一下函数是怎么走的,结果发现,每一次调用getopt_long()后的optind都是1,但是,printf的时候却不是1,下面附有gdb内容和代码。

疑惑
为什么值会不一样,是optind变量的问题,还是gdb的问题?

附加信息
gdb的内容如下
23 if (optind < argc) {
(gdb)
26 printf("optind>=argc:%d %dn", optind, argc);
(gdb)
optind>=argc:3 3
29 return 0;
(gdb) p optind
$1 = 1
(gdb) p argc
$2 = 3
代码如下:

#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    struct option longopts[] = { 
        { "testa",   no_argument, 0, 'a' },
        { "testb",  no_argument, 0, 'b' },
        { 0, 0, 0, 0 } 
    };  

    // parse command-line options
    int opt;
    while ((opt = getopt_long(argc, argv, "ab", longopts, NULL)) != -1) {
        switch(opt) {
            case 'a': printf("a\n"); break;
            case 'b': printf("b\n"); break;
            case '?':
            default : fprintf(stderr, "%s: option '%c' is invalid\n", argv[0], optopt); break;
        }   
    }   
    if (optind < argc) {
        printf("optind<argc:%d %d\n", optind, argc);
    } else {
        printf("optind>=argc:%d %d\n", optind, argc);
    }   

    return 0;
}

展开
收起
a123456678 2016-06-07 21:24:25 2621 0
1 条回答
写回答
取消 提交回答
  • 调用getopt_long()后的optind都是1,但是,printf的时候却不是

    2019-07-17 19:31:03
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
NebulaGraph图数据库在计算巢试用中心的最佳实践 立即下载
Graph图数据库基础介绍及场景 立即下载
PostgresChina2018_邵宗文_图数据库及应用场景 立即下载