C字符串的长度 - 这是有效的code? [英] C string length - is this valid code?

查看:137
本文介绍了C字符串的长度 - 这是有效的code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C这种类型的前pression有效(在所有的编译器)?
如果是,这是好的C?

Is this type of expression in C valid (on all compilers)? If it is, is this good C?

char cloneString (char clone[], char string[], int Length)
{

    if(!Length)
        Length=64
    ;

    int i = 0
    ;

    while((clone[i++] = string[i]) != '\0', --Length)
    ;

    clone[i] = '\0';

    printf("cloneString = %s\n", clone);

};

这会是更好的,更有甚者无动于衷?

Would this be better, worse, indifferent?

char *cloneString (char clone[], char string[], int Length)
{

    if(!Length)
        Length=STRING_LENGTH
    ;

    char *r = clone
    ;

    while
    (   //(clone[i++] = string[i]) != '\0'
        *clone++ = *string++
    ,   --Length
    );

    *clone = '\0';

    return clone = r
    ;

    printf("cloneString = %s\n", clone);

};

#1希望我更多的文本添加到这个问题!

Stackoverflow wants me to add more text to this question!

好吧!我担心

一)前pressions如c ==(A = B)
湾)索引之间的性能VS指针

a.) expressions such as c==(a=b) b.) performance between indexing vs pointer

任何意见?

太感谢了。

推荐答案

是的,这是对所有的编译器语法有效(虽然没有语义有效),并没有,它没有考虑好C.对于大多数开发者都认为,逗号操作符是一件坏事,大多数开发商普遍会同意,code一行应该做的只有一个具体的事情。在,而循环做一个整体的的并已未定义行为:

Yes, it's syntactically valid on all compilers (though semantically valid on none), and no, it isn't considered good C. Most developers will agree that the comma operator is a bad thing, and most developers will generally agree that a single line of code should do only one specific thing. The while loop does a whole four and has undefined behavior:


  • 它增加 I ;

  • 字符串[我] 分配给克隆[我++] ; (未定义行为:你应该使用 I 仅在一份声明中一旦递增/递减吧)

  • 它会检查字符串[我] 不为0(但丢弃比较的结果);

  • 它递减长度,并终止循环,如果长度== 0 后被递减。

  • it increments i;
  • it assigns string[i] to clone[i++]; (undefined behavior: you should use i only once in a statement that increments/decrements it)
  • it checks that string[i] isn't 0 (but discards the result of the comparison);
  • it decrements Length, and terminates the loop if Length == 0 after being decremented.

且不说假设长度 64,如果没有提供这是一个可怕的想法并留下足够的空间,可以很容易被利用来更不确定的行为崩溃或破解程序。

Not to mention that assuming that Length is 64 if it wasn't provided is a terrible idea and leaves plenty of room for more undefined behavior that can easily be exploited to crash or hack the program.

我看是你自己写的,并且你关心性能,而这显然是你粘在一起的一切的原因。的的code作了简短挤压语句组合在一起不超过code再快的,因为声明没有被挤压在一起。它仍然是同样的一些事情。在你的情况,你挤压的东西放在一起引入的错误。

I see that you wrote it yourself and that you're concerned about performance, and this is apparently the reason you're sticking everything together. Don't. Code made short by squeezing statements together isn't faster than code longer because the statements haven't been squeezed together. It still does the same number of things. In your case, you're introducing bugs by squeezing things together.

这篇关于C字符串的长度 - 这是有效的code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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